/*!
    This file is part of KapiSkript.

    Copyright (C) 2009 RaNaN

    KapiSkript is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    KapiSkript is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
const kl_version = "2.7.7";
const kl_v = 277;
var loca= new kl_language();

var kl_pref = Components.classes["@mozilla.org/preferences;1"].getService(Components.interfaces.nsIPref);

var kl_prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);


if (kl_prefManager.getBoolPref("extensions.ks.firststart")) {

    kl_prefManager.setBoolPref("extensions.ks.firststart", false);
    window.setTimeout("kl_firststart();", 5000);
}

if (kl_prefManager.getIntPref("extensions.ks.version") < kl_v) {

    kl_prefManager.setIntPref("extensions.ks.version", kl_v);
    window.setTimeout("kl_updated();", 5000);

}


// Gebäude
//annehmen vertrag9 /ablehnen vertrag10
var timeout = 0;
//Box Funktionen

//Aufruf mit: onMouseOver="info(Titel, Text);" onMouseOut="clr();"
var ziel,preis,anzahl,kaufpreis,prodInputs,umsatz,gewinn,gewinnprostueck,i,sortString,cn,k,j,aburl,anurl,loc,over,zeiten,farben,docloc,lang;
// fester Teil der Variablendeklaration

//var start,ende;

var igmforw = false;
var ausbauZahl = 0;

var x = 0;
var xx = 100;
var yy = 0;
var y = 0;
var showit = 0;
var wb = 0;
var x_name = /(.[a-zA-Za-яA-Я\.äöüÄÖÜ_&\; ]*)[ ]/;
var x_groesse = /([0-9]+)(.m²)/;
var x_quali = /\s([a-zA-Za-яA-Я\.äöüÄÖÜ_&\;\s]+)/;
var nx = 100;
var ny = 100;
var show_nb = false;
var xmlHttpRequest = false;

function wtl(doc, txt) {

    show(over);
    doc.getElementById('klDiv').innerHTML = txt;

}

//----------------------------------------------------------------------------------------------------------

function show(obj)
{
    obj.style.visibility = "visible";
}


// FUNKTION: MOUSEOUT
// clr -> hide


function hide(obj)
{
    obj.style.visibility = "hidden";

}

// EBENE BEWEGEN

function moveTo(obj, lx, ly)
{
    obj.style.left = lx + "px";
    obj.style.top = ly + "px";
    return false;
}


// FUNKTION: MOUSEOUT

function clr()
{
    showit = 0;
    hide(over);
}


// EBENE ZUSAMMENSTELLEN

function rinfo(doc, title, description)
{

    var txt = "<table cellspacing=1 cellpadding=2 border=0 width=180 bgcolor=\"#000000\">"
    + "<tr><td class=\"white\"><b>" + title + "</b></td></tr>\n"
    + "<tr><td class=\"white2\">\n"
    + description
    + "</td></tr></table>";
    wtl(doc, txt);
    display_it();
}

function kl_info(doc, title, description) {
    yy = 5;
    xx = -320;

    if (yy == -111) xx = -335;
    if (yy == -244) xx = -335;

    rinfo(doc, title, description);
}


// ANZEIGEN

function display_it() {
    if (showit == 0)
    {
        moveTo(over, x + xx, y + yy);
        show(over);
        showit = 1;
    }
}


// REAKTION AUF MAUSZEIGERBEWEGUNG

function mouseMove(e) {
    if (document.all) {
        x = window.event.x + document.documentElement.scrollLeft;
    } else {
        x = e.pageX;
    }
    if (document.all) {
        y = window.event.y +
        document.documentElement.scrollTop;
    } else {
        y = e.pageY;
    }

    if (showit) {
        moveTo(over, x + xx, y + yy);
    }
}


// Hilfsfunktionen
function kl_updated(){

    var tab = gBrowser.addTab("http://k3.morgil.de/kapi-skript.php?page=update&version="+kl_v);
    gBrowser.selectedTab = tab;
}


function kl_firststart() {
    //noinspection JSDeprecatedSymbols
    alert(unescape("Herzlichen Glückwunsch, dass du KapiSkript installiert hast. Zu den Optionen kommst du %FCber das Addonmen%FC oder indem du auf das KS Logo klickst. Vergesse nicht regelm%E3%DFig nach Update zu schauen. Und nun Viel Spaß mit dem KapiSkript! Gratulation, you have sucessfully installed KapiSkript. You can reach the preference menu through the addon menu or when you click the KapiSkript logo. Dont forget to look for updates. And now, I wish you much fun with the KapiSkript!"));
}


function sortAdress(a, b) {
    a = a.textContent;
    a = a.toLowerCase();
    a = a.replace(/ä/g, "a");
    a = a.replace(/ö/g, "o");
    a = a.replace(/ü/g, "u");
    a = a.replace(/ß/g, "s");

    b = b.textContent;
    b = b.toLowerCase();
    b = b.replace(/ä/g, "a");
    b = b.replace(/ö/g, "o");
    b = b.replace(/ü/g, "u");
    b = b.replace(/ß/g, "s");

    return(a == b) ? 0 : (a > b) ? 1 : -1;
}

function sortNeuAdress(a,b){

    a = a[0].textContent;
    a = a.toLowerCase();
    a = a.replace(/ä/g, "a");
    a = a.replace(/ö/g, "o");
    a = a.replace(/ü/g, "u");
    a = a.replace(/ß/g, "s");

    b = b[0].textContent;
    b = b.toLowerCase();
    b = b.replace(/ä/g, "a");
    b = b.replace(/ö/g, "o");
    b = b.replace(/ü/g, "u");
    b = b.replace(/ß/g, "s");

    return(a == b) ? 0 : (a > b) ? 1 : -1;

}

function sortBereit(a, b) {
    if (a.lastChild.textContent.search(loca[lang]["bereit"]) > -1 && b.lastChild.textContent.search(loca[lang]["bereit"]) > -1) return 0;
    else if (a.lastChild.textContent.search(loca[lang]["bereit"]) > -1) return -1;
    else if (b.lastChild.textContent.search(loca[lang]["bereit"]) > -1) return 1;
    else
        return (parseFloat(a.lastChild.textContent.replace(/[:]/g, "")) - parseFloat(b.lastChild.textContent.replace(/[:]/g, "")));
}

function sortSize(a, b) {
    try{
        return (parseFloat(a.textContent.match(x_groesse)[1]) - parseFloat(b.textContent.match(x_groesse)[1]));
    }catch(e){
        return 0;
    }
}

function sortProd(a, b) {
    return (parseFloat(b.childNodes[1].textContent) - parseFloat(a.childNodes[1].textContent));
}

function sortVertrag(a, b){

    if (a.nodeName.search(/(#text|SCRIPT)/i) > -1) return 1;
    if (b.nodeName.search(/(#text|SCRIPT)/i) > -1) return -1;

    a = a.childNodes[1].firstChild.textContent;
    a = a.toLowerCase();
    a = a.replace(/ä/g, "a");
    a = a.replace(/ö/g, "o");
    a = a.replace(/ü/g, "u");
    a = a.replace(/ß/g, "s");

    b = b.childNodes[1].firstChild.textContent;
    b = b.toLowerCase();
    b = b.replace(/ä/g, "a");
    b = b.replace(/ö/g, "o");
    b = b.replace(/ü/g, "u");
    b = b.replace(/ß/g, "s");

    return(a == b) ? 0 : (a > b) ? 1 : -1;

}

function kl_isKapilandDomain(location) {
    if (location.href.search(/(skybanner.php|ucp.php|schaufenster_public.php|zeitung.php|dd-hosting)/) > -1) return false;

    //lang = "de";return true; // debug

    if (location.host.search(/kapiland.*(.de)/) > -1) {
        lang = "de";
        return true;
    } else if (location.host.search(/bg.kapilands.eu/) > -1) {
        lang = "bg";
        return true;
    } else if (location.host.search(/kapilands(.eu)/) > -1) {
        lang = "de";
        return true;
    } else if (location.host.search(/kapilands.*(.com)/) > -1) {
        lang = "en";
        return true;
    } else if (location.host.search(/kapilands.*(.fr)/) > -1) {
        lang = "fr";
        return true;
    } else if (location.host.search(/kapilands.nl/) > -1) {
        lang = "nl";
        return true;
    }
    return false;
}

function kl_isWelt5(location) {
    return location.host.search(/s[56]\.kapiland/) > -1;
}

//array.sort(sortAdress);
function kl_verkstatreq(doc,w,l){
    var parameters = "";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.overrideMimeType('text/plain');
    xmlHttpRequest.onreadystatechange = function(){
        kl_verkstat(doc);
    };
    xmlHttpRequest.open('POST', "http://morgil.de/kapi-stats/ks/daten"+w+""+l+".txt", true);
    xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttpRequest.setRequestHeader("Content-length", parameters.length);
    xmlHttpRequest.setRequestHeader("Connection", "close");
    xmlHttpRequest.send(parameters);
}

function kl_verkstat(mTB){
    if (xmlHttpRequest.readyState == 4) {
        if (xmlHttpRequest.status == 200) {
            // hauptteil
            for(var i = 1;i < mTB.childNodes.length;i++){
                try{
                    var prod = mTB.childNodes[i].childNodes[0].textContent.match(/[ ]([a-zA-ZäöüÄÜÖß]*)/)[1];
                    var reg = new RegExp("([0-9a-z]*)[|]"+prod);
                    var farbe = xmlHttpRequest.responseText.match(reg)[1];
                    mTB.childNodes[i].childNodes[1].setAttribute("style","background-color:"+farbe+";");
                }
                catch(e){
                    continue;
                }
            }

            mTB.firstChild.firstChild.removeChild(mTB.firstChild.firstChild.lastChild);

        //hauptteilende
        }else{
    //fehler
    }
    }
}

function kl_statRequest(doc,w,l,s2,p3) {

    var parameters = "";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.overrideMimeType('text/plain');
    xmlHttpRequest.onreadystatechange = function(){
        kl_statStatus(doc,s2,p3);
    };
    xmlHttpRequest.open('POST', "http://morgil.de/kapi-stats/ks/daten"+w+""+l+".txt", true);
    xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttpRequest.setRequestHeader("Content-length", parameters.length);
    xmlHttpRequest.setRequestHeader("Connection", "close");
    xmlHttpRequest.send(parameters);
}

function kl_statStatus(doc,s2,p3) {
    if (xmlHttpRequest.readyState == 4) {
        if (xmlHttpRequest.status == 200) {
            // hauptteil


            var stats = xmlHttpRequest.responseText.split("\n");
            for(var i=0;i < stats.length;i++){
                stats[i] = stats[i].split("|");
            }
            var c = 0;
            if (s2) c = 35;
            var sTB = doc.getElementById("statstable");

            if (kl_prefManager.getBoolPref("extensions.ks.statsdiff")){
                sTB.childNodes[0].childNodes[0].setAttribute("width","25%");
                if (!p3){
                    for (i=1;i < sTB.childNodes.length - 1;i++){
                        sTB.childNodes[i].childNodes[0].setAttribute("width","25%");
                        sTB.childNodes[i].childNodes[1].textContent += " ("+stats[i+c-1][2]+")";
                        sTB.childNodes[i].childNodes[2].textContent += " ("+stats[i+c-1][4]+")";
                        sTB.childNodes[i].childNodes[3].textContent += " ("+stats[i+c-1][5]+")";
                    }
                }else{
                    for (i=1;i < sTB.childNodes.length - 1;i++){
                        sTB.childNodes[i].childNodes[0].setAttribute("width","25%");
                        sTB.childNodes[i].childNodes[1].textContent += " ("+stats[i+c-1][3]+")";
                        sTB.childNodes[i].childNodes[2].textContent += " ("+stats[i+c-1][2]+")";
                    }
                    }
                }
            if (kl_prefManager.getBoolPref("extensions.ks.statscol")){
                for (i=1;i < sTB.childNodes.length - 1;i++){
                    sTB.childNodes[i].childNodes[0].setAttribute("style","background-color:"+stats[i+c-1][0]);
                }
                }
            doc.getElementById("kstat").innerHTML = "<a href='http://stats.kapigeco.de'>Stats by kapigeco.de</a>";

        //hauptteilende
        } else {
            doc.getElementById("kstat").innerHTML = "Error occured";
        }
    }
}


function check(string, array)
{
    for (var i = 0; i < array.length; i++)
    {
        if (string.search(array[i]) > -1)
        {
            return true;
        }
    }
    return false;
}

function extract(code, a, b)
{
    code = code.substring(code.search(a) + a.length, code.length);
    code = code.substring(0, code.search(b));
    return code;
}


function kl_supportChoose(event){
    var doc = event.target.ownerDocument;
    var id = event.target.getAttribute("id");
    var produkt = id.substring(0,id.search("q"));

    if (event.target.checked){
        var prods = kl_eval(doc,"//input[contains(@id,'"+produkt+"') and not(@id='"+id+"')]");
        //var prods = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('id').search('"+produkt+"') > -1 && Kn.getAttribute('id') != '"+id+"');"));
        for (var i=0;i < prods.length;i++){
            prods[i].checked = false;
        }
    }else{
        event.target.checked = true;
    }

}

function kl_alles(event){

    var doc = event.target.ownerDocument;
    var max = doc.location.search.match(/lm=([0-9]+)/)[1];

    var menge = event.target.parentNode.textContent.match(/[0-9]+/);

    var inp = event.target.parentNode.parentNode.lastChild.firstChild;

    if ((max * 1) < menge) var ins = max;

    else var ins = menge;

    inp.value = ins;
}

function kl_verwk(event){

    doc = event.target.ownerDocument;
    if (event.target.getAttribute("id") == "ksvk"){

        var inputs = kl_eval(doc,"//input[@name='p_anz[]']");
        //var inputs = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'p_anz[]');"));

        for (var i =0;i < inputs.length;i++){
            if (inputs[i].value != "" && inputs[i].value != "0"){
                var row = inputs[i];
                break;
            }
        }

        var preis = row.parentNode.parentNode.childNodes[1].textContent;

        preis = preis * (event.target.value / 100);
    }else{

        anzahl = event.target.parentNode.parentNode.textContent.match(/[0-9]+/);
        event.target.parentNode.parentNode.parentNode.lastChild.lastChild.value = anzahl;
        var preis = event.target.parentNode.parentNode.parentNode.childNodes[1].textContent * (doc.getElementById("ksvk").value / 100);
    }


    kl_eval(doc,"//input[@name='preis']")[0].value = preis;

//FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'preis');"))[0].value = preis;

}

function kl_notizbuch(doc) {
    var obj = doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klNote", "style", "visibility:hidden; Z-INDEX: 5; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));
    var txt,title,description;
    var mouseclick = 0;
    var lx = -60;
    var ly = -12;
    var showit = 0;
    var self = this;
    this.change = function(){

        if (show_nb){
            self.hide();
            show_nb = false;
        }
        else{
            self.show();
            show_nb = true;
        }

    };

    this.save = function(){
        kl_prefManager.setCharPref("extensions.ks.notizcontent", obj.firstChild.firstChild.lastChild.firstChild.lastChild.firstChild.value);

    };

    this.delet = function(){
        obj.parentNode.removeChild(obj);
    };

    this.show = function()
    {
        obj.style.visibility = "visible";
        showit = 1;
    };

    this.hide = function()
    {
        obj.style.visibility = "hidden";
        showit = 0;
        show_nb = false;
    };

    this.move = function(lx,ly){
        obj.style.left = lx + "px";
        obj.style.top = ly + "px";
        return false;
    }

    this.moveTo = function(lx,ly)
    {
        nx = lx;
        ny = ly;
        obj.style.left = lx + "px";
        obj.style.top = ly + "px";
        return false;
    };

    this.down = function(event) {
        if (event.button == 0) mouseclick = 1;
    };
    this.up = function() {
        mouseclick = 0;
    };

    this.set = function()
    {
        title = loca[lang]["notizen"];
        description = "<form style ='margin-bottom: 1px; margin-left: 1px;'><textarea cols='"+kl_prefManager.getIntPref("extensions.ks.nbcols")+"' rows='"+kl_prefManager.getIntPref("extensions.ks.nbrows")+"'></textarea><input type='button' value='schließen'></input></form>";

        txt = "<table style='-moz-opacity: "+(kl_prefManager.getIntPref("extensions.ks.nbopac")/100)+"' cellspacing=1 cellpadding=2 border=0 width=250 bgcolor=\"#000000\">"
        + "<tr><td class=\"white\"><b>" + title + "</b></td></tr>\n"
        + "<tr><td class=\"white2\">\n"
        + description
        + "</td></tr></table>";
        obj.innerHTML = txt;
        obj.firstChild.firstChild.firstChild.addEventListener("mousedown",this.down,true);
        obj.ownerDocument.firstChild.lastChild.addEventListener("mouseup",this.up,true);
        obj.ownerDocument.firstChild.lastChild.addEventListener("mousemove",this.mouseMove,true);
        obj.firstChild.firstChild.lastChild.firstChild.lastChild.lastChild.addEventListener("click",this.hide,true);
        obj.firstChild.firstChild.lastChild.firstChild.lastChild.firstChild.value = kl_prefManager.getCharPref("extensions.ks.notizcontent");
        obj.firstChild.firstChild.lastChild.firstChild.lastChild.firstChild.addEventListener("keyup",this.save,true);

    };

    this.mouseMove = function(e) {
        if (mouseclick == 1){
            x = e.pageX;
            y = e.pageY;
            if (showit) {
                self.moveTo(x + lx, y + ly);
            }
            }
    };

}

/*
function kl_XPath(aNode, aExpr) {

	var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?
    aNode.documentElement : aNode.ownerDocument.documentElement);
  var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
  var found = [];
  var res;
  while (res = result.iterateNext())
    found.push(res);
  return found;

var result = aNode.evaluate(aExpr,aNode,null,0, null);

}
 */

function kl_getWelt(host){
    try{
        var welt= host.match(/(w|welt|s)([0-9]).kapiland/)[2];
    }catch(e){
        if (host.search(".h1.kapiland.de") > -1){
            var welt = 3;
        }else var welt = 1;
    }

    return welt;
}


function kl_evalNode(doc,aNode,aExpr){

    var result = doc.evaluate(aExpr,aNode,null,0, null);

    var found = [];
    var res;
    while (res = result.iterateNext())
        found.push(res);

    return found;

}

function kl_eval(aNode, aExpr){

    return kl_evalNode(aNode,aNode,aExpr);

}

function kl_int(zahl){
    try{
        zahl = zahl.replace(new RegExp("["+zahl.match(/([,.])[0-9]{3}/)[1]+"]","g"),"");
    }catch(e){}
    try{
        zahl = zahl.replace(/[,]/g,".");
    }catch(e){}

    return zahl;
}
/*function TagsRaus(Text) // Entferne die Tags aus dem Text
{
    return Text.replace(/<[^<>]*>/g, ""); // Tags entfernen
}*/
//-------------------------------------------------------------------------------
/*function IstZelle(Kn) // gibt an ob der entsprechende Knoten eine Tabellenzelle ist
{
    return (Kn.nodeName == 'TD' || Kn.nodeName == 'TH');
}*/
//-------------------------------------------------------------------------------
/*function InInt(Text) // Verwandelt den übergebenden Text in eine Ganzzahl
{
    Text = TagsRaus(Text).replace(/[^0-9\-]/g, ""); // nicht-Ziffern und Tags entfernen
    return parseInt(Text, 10); // als Zahl zurueckgeben
}*/
//-------------------------------------------------------------------------------
function FindeTags(doc, TagName, Bedingung) // Finde alle Knoten des Dokuemnts des Tags Name, die die Bedingung erfuellen
{
    var Arr = new Array(); // Arry zum Speichern
    var Tags = doc.getElementsByTagName(TagName); // Alle Tags nehmen

    for (var i = 0; i < Tags.length; ++i) { //noinspection JSUnusedLocalSymbols
        try {
            if (Bedingung(Tags[i])) { // und auf die Bedingun testen
                Arr[Arr.length] = Tags[i]; // die positiven Tags speichern
            }
        } catch(e) {
        }
    }
    return Arr; // Knoten zurueckgeben
}
//-------------------------------------------------------------------------------
/*function FindeKinder(Knoten, Bedingung, KinderEbenen) // finde alle Kindknoten dieses Knotens, die diese Bedingung erfuellen, und suche noch KinderEbenen Ebenen tiefer
{
    var Arr = new Array(); // Arry zum Speichern
    if ((typeof Bedingung) != "function") // falls die Bedingung ein String ist, mache sie zu einer Funktion, die dieses Tag als true nimmt und den Rest als falsch
        Bedingung = new Function("Kn", 'return (Kn.nodeName=="' + Bedingung.toUpperCase() + '");');
    for (var i = 0; i < Knoten.childNodes.length; ++i) { // ueber alle Kindknoten
        if (Bedingung(Knoten.childNodes[i])) // Bedingung testen
            Arr[Arr.length] = Knoten.childNodes[i]; // falls positiv, speichern
        if (KinderEbenen) // falls berhaupt Unterbenen getestet werden sollen
            Arr = Arr.concat(FindeKinder(Knoten.childNodes[i], Bedingung, KinderEbenen - 1)); // eine Ebene tiefer, daher eine weniger testen
    }
    return Arr; // Knoten zurueckgeben
}*/
//-------------------------------------------------------------------------------
// Die Funktion ist statisch und die dynamischen Dinge sind via globaler Variable festgelegt - unsauber, aber es klappt
var AnzSpalt; // Anzahl der Spalten die die Tabelle haben muss
/*function ZeileRichtig(Kn) // Gibt an ob diese Tabellenzelle richtig ist
{
    return (FindeKinder(Kn, IstZelle, 1).length == AnzSpalt); // es muss eine Tabellenzeile sein und die Anzahl der Zellen muss stimmen
}
/*function FindeTabZeilen(doc, Spalten) // Eigentliche Funktion
{
    AnzSpalt = Spalten; // Anzahl Spalten weitergeben
    return FindeTags(doc, "tr", ZeileRichtig, -1); // Tabellenzeilen finden
}*/
//-------------------------------------------------------------------------------
function NeuesElement(doc, Tag, Inhalt) // erstellt ein neues Tag
{
    var Neu = doc.createElement(Tag); // erste Zelle (Titel)
    if (Inhalt.indexOf("<") != -1 || Inhalt.indexOf("&") != -1) // falls Tags oder &;-Umschreibungen im Text sind
        Neu.innerHTML = Inhalt; // Text als HTML-Code
    else if (Inhalt.length > 0) // ansonsten, und falls es ueberhaupt einen Text gibt
        Neu.appendChild(doc.createTextNode(Inhalt)); // Text als Attribut

    if (arguments.length > 3) { // weitere Argumente der Funktion
        for (var i = 3; i < arguments.length - 1; i += 2) { // alle diese Argumente
            if (!arguments[i + 1].length) continue;
            Neu.setAttribute(arguments[i], arguments[i + 1]); // dem Tag zuweisen
        }
    }

    return Neu; // zurueckgeben
}
//--------------------------------------------------
function EinfuegenHinter(Neu, Hinter) // fuege des neue Element hinter dem anderen ein
{
    Hinter.parentNode.insertBefore(Neu, Hinter.nextSibling); // Element einfuegen
    return Neu; // Element zurueckgeben
}
//-------------------------------------------------------------------------------
function GetY(element) // gibt die Y-Koordinate des angegebenen Elemnts zurueck
{
    return element.offsetTop + (element.nodeName == "BODY" ? 0 : GetY(element.offsetParent)); // aktueller offset + den des Vorgaengers, falls wir nicht schon beim Body-Tag sind
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
function Loesche(element) // Loesche dieses Element
{
    element.parentNode.removeChild(element); // Da nur Kindelemente geloescht werden koennen, wird vom Elternknoten her geloescht
}
//-------------------------------------------------------------------------------

//--------------------------------------------------

/*function ntesKind(Knoten, ziel_n, Bedingung) // n. Kind das diese Bedinung erfuellt finden
{
    if ((typeof Bedingung) != "function") // falls die Bedingung ein String ist, mache sie zu einer Funktion, die dieses Tag als true nimmt und den Rest als falsch
        Bedingung = new Function("Kn", 'return (Kn.nodeName=="' + Bedingung.toUpperCase() + '");');
    var n = 0; // n. Kind das gefunden wurde
    for (var i = 0; i < Knoten.childNodes.length; ++i) { // ueber alle Kindknoten
        if (Bedingung(Knoten.childNodes[i])) { // falls die Bedingung erfuellt wurde
            ++n; // n erhoehen
            if (n >= ziel_n) return Knoten.childNodes[i]; // falls es das n. Kind ist, zurueckgeben
        }
    }
    return false;
}*/

function absLeft(el) {
    return (el.offsetParent) ?
    el.offsetLeft + absLeft(el.offsetParent) : el.offsetLeft;
}

function absTop(el) {
    return (el.offsetParent) ?
    el.offsetTop + absTop(el.offsetParent) : el.offsetTop;
}
//-------------------------------------------------------------------------------
function kl_getQuali(doc,lang){

    try{
        return kl_prefManager.getCharPref("extensions.ks.verwq").match(new RegExp(kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"[(]([0-9|]+)[)];"))[1].split("|")[1];
    }catch(e){
        return 0;
    }

}

function kl_saveQuali(event){

    var doc = event.target.ownerDocument;


    if (event.target.name == "vq"){
        var quali = event.target.value;
        var produkt = kl_eval(doc,"//select[@name='vprod']")[0].selectedIndex;
    }else{
        var quali = kl_eval(doc,"//input[@name='vq']")[0].value;
        var produkt =  event.target.selectedIndex;
    }


    var save = kl_prefManager.getCharPref("extensions.ks.verwq");

    if (save.search(new RegExp(kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"[(]([0-9|]+)[)];")) > -1){

        save = save.replace(new RegExp(kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"[(]([0-9|]+)[)];"),kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"("+produkt+"|"+quali+")"+";");

    }else{
        save += kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"("+produkt+"|"+quali+")"+";";
    }

    kl_prefManager.setCharPref("extensions.ks.verwq",save);

}

function kl_getProdukt(doc,lang){

    try{
        return kl_prefManager.getCharPref("extensions.ks.verwq").match(new RegExp(kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"[(]([0-9|]+)[)];"))[1].split("|")[0];
    }catch(e){
        return 0;
    }

}


function kl_addEvent(obj, type, fn) {
    if (obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function() {
            obj['e' + type + fn](window.event);
        };
        obj.attachEvent('on' + type, obj[type + fn]);
    } else
        obj.addEventListener(type, fn, true);
}

/*
Math.setSectionPoints = function (z) {
    var z1 = String(z).split(".");
    if (z1[0].length <= 3) return z1.join(",");
    var i_array = z1[0].split("").reverse();
    var o_array = new Array();
    o_array.push("," + z1[1]);
    var count = 0;
    for (var i = 0; i < i_array.length; i++) {
        o_array.push(i_array[i]);
        count++;
        if (count == 3) {
            o_array.push(".");
            count = 0;
        }
    }
    z = o_array.reverse().join("");
    if (z.substring(0, 1) == ".") z = z.substring(1, z.length);
    if (z.search("undefined") > -1)z = z.substring(0, z.search("undefined") - 1);
    return z;
};*/




Math.setSectionPoints = function (z) {
    var z1 = String(z).split(".");
    if (z1[0].length <= 3) return z1.join(loca[lang]["komma"]);
    var i_array = z1[0].split("").reverse();
    var o_array = new Array();
    o_array.push(loca[lang]["komma"] + z1[1]);
    var count = 0;
    for (var i = 0; i < i_array.length; i++) {
        o_array.push(i_array[i]);
        count++;
        if (count == 3) {
            o_array.push(loca[lang]["punkt"]);
            count = 0;
        }
    }
    z = o_array.reverse().join("");
    if (z.substring(0, 1) == loca[lang]["punkt"]) z = z.substring(1, z.length);
    if (z.search("undefined") > -1) z = z.substring(0, z.search("undefined") - 1);
    return z;
};
/////////////////////////////
// Berechnunsfunktionen
/////////////////////////////
function kl_forschZeit(event) {

    var doc = event.target.ownerDocument;
    over = doc.getElementById("klDiv");
    var zeit = event.target.parentNode.previousSibling.textContent;
    var stunden = extract(zeit, loca[lang]["zeit"]+" ", " ");
    var minuten = extract(zeit, loca[lang]["stunde"]+" ", " ");

    var dauer = (stunden * 60 * 60 + minuten * 60) * 1000;

    var FertigZeit = new Date();
    FertigZeit.setTime(FertigZeit.getTime() + dauer);

    var Wochentag = loca[lang]["wochentag"];

    var zeitString = Wochentag[FertigZeit.getDay()] + " " +
    ((FertigZeit.getDate() < 10) ? "0" + FertigZeit.getDate() : FertigZeit.getDate())
    + "." + (((parseFloat(FertigZeit.getMonth()) + 1) < 10) ? "0" + (parseFloat(FertigZeit.getMonth()) + 1) : (parseFloat(FertigZeit.getMonth()) + 1))
    + " " + ((FertigZeit.getHours() < 10) ? "0" + FertigZeit.getHours() : FertigZeit.getHours()) + ":" + ((FertigZeit.getMinutes() < 10) ? "0" + FertigZeit.getMinutes() : FertigZeit.getMinutes());

    kl_info(doc, loca[lang]["endzeit"], zeitString);

}

function kl_BerechneProdZeit(event) {

    if (event.target.getAttribute("size") == 8) {
        anzahl = kl_evalNode(event.target.ownerDocument,event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode,".//input[@size='9']");
        //anzahl = FindeTags(event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode, "INPUT", new Function("Kn", "return (Kn.getAttribute('size') == 9);"));
        ziel = anzahl[0];
        anzahl = anzahl[0].value;

    }
    else {
        ziel = event.target;
        anzahl = event.target.value;
    }
    // Hole produktion pro sekunde
    var FontKlein = kl_evalNode(event.target.ownerDocument,event.target.parentNode.parentNode,".//font");
    //var FontKlein = FindeTags(event.target.parentNode.parentNode, "FONT", new Function("Kn", "return (Kn.nodeName == 'FONT');"));
    //var FontKlein = FindeKinder(event.target.parentNode.parentNode,"FONT",5);

    var ProdZeit = FontKlein[0].parentNode.lastChild.textContent;

    ProdZeit = ProdZeit.substring(ProdZeit.search(loca[lang]["prostunde"])+loca[lang]["prostunde"].length + 1, ProdZeit.length);

    var ProdDauer = 3600 / ProdZeit;
    ProdDauer = ProdDauer * anzahl * 1000;


    var FertigZeit = new Date();
    FertigZeit.setTime(FertigZeit.getTime() + ProdDauer);

    var Wochentag = loca[lang]["wochentag"];

    var zeitString = Wochentag[FertigZeit.getDay()] + " " +
    ((FertigZeit.getDate() < 10) ? "0" + FertigZeit.getDate() : FertigZeit.getDate())
    + "." + (((parseFloat(FertigZeit.getMonth()) + 1) < 10) ? "0" + (parseFloat(FertigZeit.getMonth()) + 1) : (parseFloat(FertigZeit.getMonth()) + 1))
    + " " + ((FertigZeit.getHours() < 10) ? "0" + FertigZeit.getHours() : FertigZeit.getHours()) + ":" + ((FertigZeit.getMinutes() < 10) ? "0" + FertigZeit.getMinutes() : FertigZeit.getMinutes());
    ziel.nextSibling.textContent = zeitString;

}
// berechnet produktion in bestimmter zeit
function kl_BerechneProduktion(event) {
    var doc = event.target.ownerDocument;

    var zeit = event.target.value;
    zeit = zeit.replace(/[,]/g,":");

    if (zeit.search(":") < 0) {
        var ProdZeit = zeit * 60;
    } else {
        zeit = zeit.split(":");
        if (zeit.length == 2) {
            var ProdZeit = zeit[0] * 60 * 60 + zeit[1] * 60;
        } else  var ProdZeit = zeit[0] * 24 * 60 * 60 + zeit[1] * 60 * 60 + zeit[2] * 60;
    }


    var SekProProdukt;
    if (kl_isWelt5(doc.location)) {
        var div = doc.getElementById("SPAN_PRODUKT_PRODUZIEREN_PLATZHALTER");
        td = div.getElementsByTagName("td")[4].textContent;
        td.search(/([0-9.]+)[^0-9]*$/);
        SekProProdukt = RegExp.$1;
    } else {
        SekProProdukt = event.target.parentNode.lastChild.textContent; // variablen namen passen nicht mehr
        SekProProdukt = SekProProdukt.substring(SekProProdukt.search(loca[lang]["prostunde"]) +loca[lang]["prostunde"].length +1, SekProProdukt.length);

    }

    var Sek = 3600 / SekProProdukt;

    var Produkte = ProdZeit / Sek;
    Produkte = Math.round(Produkte);


    var ProduktEingabe;
    if (kl_isWelt5(doc.location)) {
        ProduktEingabe = kl_eval(doc,"//tr[@style='']/td/input[@name='a_bestellen[]']")[0];
    } else {
        var Zeile = event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;

        ProduktEingabe = Zeile.lastChild.firstChild;
    }

    ProduktEingabe.value = Produkte;

}

function kl_BerechneKosten(event) {

    var doc = event.target.ownerDocument;
    var anzahl = event.target.value;

    var td = event.target.parentNode.parentNode;
    var preis = td.textContent.match(loca[lang]["zumpreisvon"])[2];

    var kosten = preis * anzahl;

    kosten = Math.round(kosten * 100) / 100;

    kosten = Math.setSectionPoints(kosten);

    doc.getElementById("gesamtkosten").textContent = loca[lang]["gesamtkosten"] + kosten + " "+loca[lang]["c"];
}

function kl_BerechneUmsatz(event) {

    var doc = event.target.ownerDocument;

    if (event.target.getAttribute("id") == "preis") {
        preis = event.target.value;
        preis = preis.replace(/[,]/g, ".");

        var mainTable = kl_eval(doc,"//td/form/table");
        //var mainTable = FindeTags(doc, "TABLE", new Function("Kn", "return (Kn.parentNode.nodeName == 'FORM' && Kn.parentNode.parentNode.nodeName == 'TD');"));

        var mainTB = mainTable[0].firstChild;

        for (var i = 1; i < mainTB.childNodes.length; i++) {
            try{
                if (mainTB.childNodes[i].lastChild.firstChild.value != "" && mainTB.childNodes[i].lastChild.firstChild.value != "0") {
                    anzahl = mainTB.childNodes[i].lastChild.firstChild.value;
                    kaufpreis = mainTB.childNodes[i].childNodes[1].textContent;
                    break;
                }
                }catch(e){
                continue;
            }

        }
    } else {
        anzahl = event.target.value;
        preis = doc.getElementById("preis").value;
        preis = preis.replace(loca[lang]["tausend"], ".");
        kaufpreis = event.target.parentNode.parentNode.childNodes[1].textContent;
    }

    var umsatz = anzahl * preis;
    var gewinn = (preis * 1 - kaufpreis * 1) * anzahl;
    var gewinnprostueck = (preis * 1 - kaufpreis * 1);

    umsatz = Math.round(umsatz * 100) / 100;
    gewinn = Math.round(gewinn * 100) / 100;
    gewinnprostueck = Math.round(gewinnprostueck * 100) / 100;

    umsatz = Math.setSectionPoints(umsatz);
    gewinn = Math.setSectionPoints(gewinn);
    gewinnprostueck = Math.setSectionPoints(gewinnprostueck);

    doc.getElementById("umsatz").textContent = loca[lang]["umsatz"] + umsatz + " "+loca[lang]["c"]+"  "+loca[lang]["gewinn"]+":" + gewinn + " "+loca[lang]["c"]+" "+ loca[lang]["gewinnps"] + gewinnprostueck + " "+loca[lang]["c"];

}

function empty(event) {
    event.target.value = "";
}

function kl_lager(event) {

    var doc = event.target.ownerDocument;

    if (event.target.getAttribute("name") == "wbet") {
        preis = event.target.value;
        preis = preis.replace(/[,]/g, ".");


        prodInputs = kl_eval(doc,"//input[@name='p_anz[]']");

        //prodInputs = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'p_anz[]');"));

        for (i = 0; i < prodInputs.length; i++) {
            if (prodInputs[i].value != "" && prodInputs[i].value != "0") {
                anzahl = prodInputs[i].value;
                kaufpreis = prodInputs[i].parentNode.previousSibling.textContent.substring(0, prodInputs[i].parentNode.previousSibling.textContent.length - 2);
                kaufpreis = kaufpreis.replace(loca[lang]["komma"], "");
                kaufpreis = kaufpreis.replace(loca[lang]["tausend"], "");
                kaufpreis = kaufpreis / 100;
                break;
            }
        }

        umsatz = anzahl * preis * 0.9;
        gewinn = (preis * 0.9 - kaufpreis * 1) * anzahl;
        gewinnprostueck = (preis * 0.9 - kaufpreis * 1);

    } else if (event.target.getAttribute("name") == "vbet") {

        preis = event.target.value;
        preis = preis.replace(/[,]/g, ".");

        var prodInputs = kl_eval(doc,"//input[@name='p_anz[]']");
        //  var prodInputs = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'p_anz[]');"));

        for (i = 0; i < prodInputs.length; i++) {
            if (prodInputs[i].value != "" && prodInputs[i].value != "0") {
                anzahl = prodInputs[i].value;
                kaufpreis = prodInputs[i].parentNode.previousSibling.textContent.substring(0, prodInputs[i].parentNode.previousSibling.textContent.length - 2);
                kaufpreis = kaufpreis.replace(",", "");
                while (kaufpreis.search(/[.]/) > -1) {
                    kaufpreis = kaufpreis.replace(".", "");
                }
                kaufpreis = kaufpreis / 100;
                break;
            }
        }

        umsatz = anzahl * preis;
        gewinn = (preis * 1 - kaufpreis * 1) * anzahl;
        gewinnprostueck = (preis * 1 - kaufpreis * 1);

    }
    else {

        anzahl = event.target.value;
        kaufpreis = event.target.parentNode.previousSibling.textContent.substring(0, event.target.parentNode.previousSibling.textContent.length - 2);
        kaufpreis = kaufpreis.replace(loca[lang]["komma"], "");
        kaufpreis = kaufpreis.replace(loca[lang]["tausend"], "");
        kaufpreis = kaufpreis / 100;

        var preisInput = kl_eval(doc,"//input[@name ='wbet' or @name='vbet']");
        //var preisInput = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'wbet' || Kn.getAttribute('name') == 'vbet');"));

        for (i = 0; i < preisInput.length; i++) {
            if (preisInput[i].value != "" && preisInput[i].value != "0") {
                var preis = preisInput[i].value;
                preis = preis.replace(/[,]/g, ".");
                if (preisInput[i].getAttribute("name") == "wbet")
                {
                    umsatz = anzahl * preis * 0.9;
                    gewinn = (preis * 0.9 - kaufpreis * 1) * anzahl;
                    gewinnprostueck = (preis * 0.9 - kaufpreis * 1);


                } else {
                    umsatz = anzahl * preis;
                    gewinn = (preis * 1 - kaufpreis * 1) * anzahl;
                    gewinnprostueck = (preis * 1 - kaufpreis * 1);

                }

                break;
            }
        }

    }

    umsatz = Math.round(umsatz * 100) / 100;
    gewinn = Math.round(gewinn * 100) / 100;
    gewinnprostueck = Math.round(gewinnprostueck * 100) / 100;

    umsatz = Math.setSectionPoints(umsatz);
    gewinn = Math.setSectionPoints(gewinn);
    gewinnprostueck = Math.setSectionPoints(gewinnprostueck);

    doc.getElementById("gewinn").textContent = loca[lang]["umsatz"] + umsatz + " "+loca[lang]["c"]+"  "+loca[lang]["gewinn"]+":" + gewinn + " "+loca[lang]["c"]+" "+ loca[lang]["gewinnps"] + gewinnprostueck + " "+loca[lang]["c"];

}

function kl_alleWaren(event) {

    var tr = event.target.parentNode.parentNode;
    var WarenAnzahl = tr.firstChild.lastChild.textContent;
    WarenAnzahl = WarenAnzahl.replace(/[,.]/g, "");
    WarenAnzahl = WarenAnzahl.replace(/\s/g, "");
    event.target.parentNode.firstChild.value = WarenAnzahl;
    event.target.parentNode.firstChild.focus();
}

function kl_ausbau(event) {

    var anzahl = event.target.value;

    var td = event.target.parentNode.parentNode.firstChild;

    var preis = td.textContent.match(loca[lang]["prodkost"])[2];
    preis = preis.replace(loca[lang]["tausend"], "");

    var stunde = td.textContent.match(loca[lang]["prodh"])[2];
    var minute = td.textContent.match(loca[lang]["prodmin"])[2];
    var steine = td.textContent.match(loca[lang]["prodsteine"])[2];
    var stahl = td.textContent.match(loca[lang]["prodstahl"])[2];
    var holz = td.textContent.match(loca[lang]["prodholz"])[2];

    var gesPreis = preis * anzahl;

    gesPreis = Math.round(gesPreis * 100) / 100;
    gesPreis = Math.setSectionPoints(gesPreis);

    var dauer = stunde * 60 + (minute * anzahl);

    var gesSteine = steine * anzahl;
    gesSteine = Math.setSectionPoints(gesSteine);
    var gesStahl = stahl * anzahl;
    gesStahl = Math.setSectionPoints(gesStahl);
    var gesHolz = holz * anzahl;
    gesHolz = Math.setSectionPoints(gesHolz);


    var output = loca[lang]["kosten"]+" " + gesPreis + loca[lang]["c"] + unescape("%A0%A0") + loca[lang]["dauer"]+" " + Math.floor(dauer / 60) + loca[lang]["stundenund"] + (dauer % 60) + loca[lang]["minuten"];

    var output2 = loca[lang]["steine"]+": " + gesSteine + unescape("%A0%A0") + loca[lang]["stahl"]+": " + gesStahl + unescape("%A0%A0") + loca[lang]["holz"]+": " + gesHolz;

    event.target.ownerDocument.getElementById("kosten").textContent = output;
    event.target.ownerDocument.getElementById("kosten2").textContent = output2;
}

function kl_berechneGewinn(event) {

    var gewinn = event.target.value;

    var mainTable = kl_eval(event.target.ownerDocument,"//td/form/table");

    //var mainTable = FindeTags(event.target.ownerDocument, "TABLE", new Function("Kn", "return (Kn.parentNode.nodeName == 'FORM' && Kn.parentNode.parentNode.nodeName == 'TD');"));

    var mainTB = mainTable[0].firstChild;

    for (var i = 1; i < mainTB.childNodes.length; i++) {
        if (mainTB.childNodes[i].lastChild.firstChild.value != "" && mainTB.childNodes[i].lastChild.firstChild.value != "0") {
            //var anzahl = mainTB.childNodes[i].lastChild.firstChild.value;
            var kaufpreis = mainTB.childNodes[i].childNodes[1].textContent;

            break;
        }
    }
    if (gewinn < 100) {
        preis = Math.round(gewinn * kaufpreis * 100) / 100;
    } else preis = Math.round(gewinn * kaufpreis) / 100;

    event.target.ownerDocument.getElementById("preis").setAttribute("value", preis);

}

function kl_ProdKosten(event) {
    var doc = event.target.ownerDocument;
    over = doc.getElementById("klDiv");
    /*
    <tr><td width=60><b>Produkt: </b></td><td>100 Gold Qualität 0</td></tr><tr><td width=60><b>Einzelpreis: </b></td><td width=200>0.00 ¢</td></tr><tr><td width=60><b>Gesamtpreis: </b></td><td>0.00 ¢</td></tr></tr></table>
     */
    var code = "<table border=0 width=180 cellpadding=0 cellspacing=0>";

    var ben = kl_evalNode(doc,event.target.parentNode.parentNode,".//font[@class='klein']");

    //var ben = FindeTags(event.target.parentNode.parentNode, "FONT", new Function("Kn", "return (Kn.getAttribute('class') == 'klein');"));
    var mainTB = ben[0].parentNode;

    if (event.target.getAttribute("size") == 8){
        anzahl = kl_evalNode(doc,event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode,".//input[@size ='9']")[0].value;

    //anzahl = FindeTags(event.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode, "INPUT", new Function("Kn", "return (Kn.getAttribute('size') == 9);"))[0].value;
    } else anzahl = event.target.value;

    if (ben[0].textContent.search(loca[lang]["tigt"]) > -1)
    {
        var kosten = ben[0].textContent.substring(ben[0].textContent.search(loca[lang]["tigt"]) + loca[lang]["tigt"].length, ben[0].textContent.length);
        var produkt = new Array();
        var produktanzahl = new Array();

        for (var i = 0; kosten.search(/[0-9]/) > -1; i++) {

            produktanzahl[i] = kosten.substring(kosten.search(/[0-9]/), kosten.search(/[a-za-я]/i) - 1);
            kosten = kosten.substring(kosten.search(/[a-za-я]/i), kosten.length);
            if (kosten.search(/[0-9]/) > -1) {
                produkt[i] = kosten.substring(kosten.search(/[a-za-я]/i), kosten.search(/[0-9]/));
                kosten = kosten.substring(kosten.search(/[0-9]/), kosten.length);
            } else produkt[i] = kosten;
        }
        for (i = 0; i < produkt.length; i++)
        {
            code += "<tr><td>" + Math.setSectionPoints(produktanzahl[i] * anzahl) + " " + produkt[i] + "</td></tr>";
        }
    }

    var stkosten = extract(mainTB.textContent, loca[lang]["prodkosten"], " "+loca[lang]["c"]);
    stkosten = stkosten.replace(loca[lang]["tausend"], "");
    stkosten = stkosten.replace(loca[lang]["komma"], ".");
    code += "<tr><td>" + Math.setSectionPoints(Math.round(stkosten * anzahl * 100) / 100) + " "+loca[lang]["c"]+"</td></tr></table>";

    kl_info(doc, Math.setSectionPoints(anzahl) + " " + mainTB.firstChild.textContent, code);

}

function kl_ad(event) {
}

function kl_igmPopup(event){

    var doc = event.target.ownerDocument;
    over = doc.getElementById("klDiv");

    if (doc.location.href.search(/page=adress_notizbuch(&|$)/) > -1){
        var empf = event.target.parentNode.parentNode.firstChild.textContent;
    }else if (doc.location.href.search(/page=vertrag(&|$)/) > -1){
        var empf = event.target.nextSibling.textContent;

    }
    else{
        var empf = event.target.parentNode.firstChild.textContent;
    }

    var code = "<form method='post' action='"+doc.location.pathname.substring(1,doc.location.pathname.length)+"?page=nachricht2&x&y&UIN="+ doc.body.innerHTML.match(/UIN=([0-9a-z]+)(&|")/)[1] +"' style='margin: 1px;'><table border=0 width=180 cellpadding=0 cellspacing=0>";

    code += "<tr align='center'><td><input type='hidden' name='filled' value='1'><input name='fname' type='hidden' value='"+empf+"'>"+loca[lang]["betreff"]+"<input type='text' maxlength='50' name='betreff' size='30'></td></tr>";

    code += "<tr><td><textarea name='text' cols='35' rows='10'></textarea></td></tr>";

    code += "<tr><td><input type='submit' class='send' id='igmsend' value='"+loca[lang]["senden"]+"'><input type='submit' class='send' id='igmclose' value='"+loca[lang]["schlieszen"]+"' onclick='return false;' style='margin-left: 10px;'></td></tr>";

    code += "</table></form>";


    moveTo(over, absLeft(event.target) + 54, absTop(event.target) - 15);
    kl_info(doc,loca[lang]["igm"] + empf,code);
    moveTo(over, absLeft(event.target) + 54, absTop(event.target) - 15);

    doc.getElementById("igmsend").addEventListener("click",function(event){
        igmforw = true;
    },true);
    doc.getElementById("igmsend").addEventListener("click",kl_signatur,true);
    doc.getElementById("igmclose").addEventListener("click",function(event){
        clr();
    },true);

}

function kl_getString(prefs, name) {
  return prefs.getComplexValue(name, Components.interfaces.nsISupportsString).data;
}

function kl_signatur(event){

    var doc = event.target.ownerDocument;

    var textarea = kl_eval(doc,"//textarea[@name='text']")[0];

    //var textarea = FindeTags(doc, "TEXTAREA", new Function("Kn", "return (Kn.getAttribute('name') == 'text');"))[0];

    var empf = kl_eval(doc,"//input[@name='fname']")[0].value;

    //var empf = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'fname');"))[0].value;

    var firma = doc.getElementsByTagName("b")[0].textContent;

    if (kl_prefManager.getBoolPref("extensions.ks.sigvorakt")) {

        textarea.value = kl_getString(kl_prefManager, "extensions.ks.sigvor") + "\n" + textarea.value;

    }

    if (kl_prefManager.getBoolPref("extensions.ks.signachakt")) {

        textarea.value += "\n" + kl_getString(kl_prefManager, "extensions.ks.signach");

    }

    textarea.value = textarea.value.replace(/%firma%/g,empf);
    textarea.value = textarea.value.replace(/%name%/g,firma);

}

function kl_fastAccess(event) {

    if (event.button == 2 ) {

        var doc = event.target.ownerDocument;
        over = doc.getElementById('klDiv');

        var ziel = event.target;

        var code = "<table border=0 width=180 cellpadding=0 cellspacing=0>";

        // "<tr><td></td></tr>"

        if (ziel.getAttribute("href").search(/page=forschen(&|$)/) > -1) {

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=forschen", "page=forschen3") + "'>Forscher ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=forschen", "page=forschen7") + "'>Fläche ausbauen</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=forschen", "page=forschen5") + "'>Gebäude verkaufen</a></td></tr>";

        } else if (ziel.getAttribute("href").search(/page=roh(&|$)/) > -1) {

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=roh", "page=roh12") + "'>Qualität einstellen</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=roh", "page=roh3") + "'>Arbeiter bearbeiten</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=roh", "page=roh7") + "'>Gebäude ausbauen</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=roh", "page=roh5") + "'>Gebäude verkaufen</a></td></tr>";

        } else if (ziel.getAttribute("href").search(/page=kauf(&|$)/) > -1) {

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=kauf", "page=kauf5") + "&lm=99999" + "'>im Verkauf ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=kauf", "page=kauf11") + "'>Werbung ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=kauf", "page=kauf3") + "'>Personal ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=kauf", "page=kauf7") + "'>VK Fläche ausbauen</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=kauf", "page=kauf5") + "'>Gebäude verkaufen</a></td></tr>";

        } else if (ziel.getAttribute("href").search(/page=oeffent(&|$)/) > -1) {

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=oeffent", "page=oeffent2") + "'>Auftrag ausführen</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=oeffent", "page=oeffent3") + "'>Personal ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=oeffent", "page=oeffent7") + "'>Fläche ausbauen</a></td></tr>";
        } else if (ziel.getAttribute("href").search(/page=spez(&|$)/) > -1) {


            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=spez", "page=spez3") + "'>Personal ändern</a></td></tr>";

            code += "<tr><td><a href='" + ziel.getAttribute("href").replace("page=spez", "page=spez7") + "'>Fläche ausbauen</a></td></tr>";
        }
        code += "</table>";
        moveTo(over, absLeft(event.target) + 54, absTop(event.target) - 15);
        kl_info(doc, "Funktionen", code);
        moveTo(over, absLeft(event.target) + 54, absTop(event.target) - 15);

    }
}

function kl_berechneWerbung(event) {
    var doc = event.target.ownerDocument;
    var werbepunkte = event.target.value * (parseFloat(event.target.parentNode.previousSibling.textContent) + 1);
    doc.getElementById("wb").textContent = loca[lang]["wb"]+ werbepunkte;
}
function kl_alleBereiten(event){

    var doc = event.target.ownerDocument;

    var bereite = kl_eval(doc,"//td[text() = '"+loca[lang]["fertig"]+"']/following-sibling::td/input");

    //var bereite = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('type') == 'checkbox' && Kn.parentNode.previousSibling.textContent == '"+loca[lang]["fertig"]+"');"));

    if (event.target.checked){
        for(var i = 0;i < bereite.length;i++){
            bereite[i].checked = true;
        }
    }else{
        for(i = 0;i < bereite.length;i++){
            bereite[i].checked = false;
        }
    }

}

function kl_alleq(event){

    var doc = event.target.ownerDocument;
    var qm = event.target.parentNode.getAttribute("id").match(/[0-9]+/);

    var bereite = kl_eval(doc,"//input[@type='checkbox']/../../*[contains(text(),'"+qm+"m²') or contains(text(),'"+qm+" m²')]/..//input");

    if (event.target.getAttribute("checked") == "true"){
        for(var i = 0;i < bereite.length;i++){
            bereite[i].checked = false;
            event.target.setAttribute("checked","false");
        }
    }else{
        for(i = 0;i < bereite.length;i++){
            bereite[i].checked = true;
            event.target.setAttribute("checked","true");
        }
    }


}

function kl_alleqBereite(event){

    var doc = event.target.ownerDocument;
    var qm = event.target.parentNode.getAttribute("id").match(/[0-9]+/);

    var bereite = kl_eval(doc,"//input[@type='checkbox']/../../*[contains(text(),'"+loca[lang]["fertig"]+"')]/../*[contains(text(),'"+qm+"m²') or contains(text(),'"+qm+" m²')]/..//input");

    if (event.target.getAttribute("checked") == "true"){
        for(var i = 0;i < bereite.length;i++){
            bereite[i].checked = false;
            event.target.setAttribute("checked","false");
        }
    }else{
        for(i = 0;i < bereite.length;i++){
            bereite[i].checked = true;
            event.target.setAttribute("checked","true");
        }
    }


}

function kl_adminAusbau(event){

    var doc = event.target.ownerDocument;
    var qm = event.target.value;

    var mTB = kl_eval(doc,"//td/div/form/table/tbody")[0];

    var string = kl_eval(doc,"//td/div/form/table/tbody/../../text()");
    var text = "";
    for (var i=0;i < string.length;i++){
        text += string[i].textContent;
    }

    var steine = ausbauZahl * qm * text.match(/[0-9]+/g)[0];
    var stahl = ausbauZahl * qm * text.match(/[0-9]+/g)[1];
    var holz = ausbauZahl * qm * text.match(/[0-9]+/g)[2];
    mTyp = new Array("",holz,steine,stahl);

    doc.getElementById("qmfont").textContent = " ≙ "+Math.setSectionPoints(qm*ausbauZahl)+" m²";

    var diff;

    for(var i=1;i < mTB.childNodes.length;i++){

        try{
            diff = kl_int(mTB.childNodes[i].firstChild.textContent) - mTyp[parseFloat(mTB.childNodes[i].firstChild.getAttribute("mtyp"))] * 1;
            if (diff > 0) {
                diff = "+"+Math.setSectionPoints(diff);
                mTB.childNodes[i].childNodes[1].setAttribute("style","color: darkgreen");
            }
            else{
                diff = "-"+Math.setSectionPoints(Math.abs(diff));
                mTB.childNodes[i].childNodes[1].setAttribute("style","color: darkred");
            }
            mTB.childNodes[i].childNodes[1].textContent = diff;
        }catch(e){
            continue;
        }


    }

}

function kl_prodPremium(event){

    var doc = event.target.ownerDocument;

    try{
        var prodPref = kl_prefManager.getCharPref("extensions.ks.verwaltpref").match(new RegExp(kl_getWelt(doc.location.host)+lang+doc.location.href.match(/art=([0-9]+)./)[1]+"[(]([0-9.|]+)[)]"))[1];
    }catch(e){
        var prodPref ="||||||||||||";
        alert(loca[lang]["pref"]);
        window.openDialog("chrome://kapiland/content/verwalt.xul",
            "verwPref", "chrome",
            {
                art: doc.location.href.match(/art=([0-9]+)./)[1],
                produkte: kl_eval(doc,"//select[@name='vprod']/option"),
                lang: lang,
                welt: kl_getWelt(doc.location.host),
                gBrowser : gBrowser
            });
    }
    prodPref = prodPref.split("|");

    if (doc.location.href.match(/art=([0-9]+)./)[1] == "50" || doc.location.href.match(/art=([0-9]+)./)[1] == "52"){
        var ofaktor = 0.0833;
    }else var ofaktor = 0.0625;


    if (event.target.getAttribute("name") == "vprod"){

        var zeit = kl_eval(doc,"//td[contains(@id,'kq')]/input");

        for (var i=0;i < zeit.length;i++){

            if (zeit[i].value != "" && zeit[i].value != "DD:HH:MM"){
                var qm = zeit[i].parentNode.getAttribute("id").match(/[0-9]+/);
                var arbeiter = Math.floor(qm / 10);
                zeit = zeit[i].value;
                break;
            }

        }
        var produkt = event.target.selectedIndex;


    }else{
        var zeit = event.target.value;

        var produkt = kl_eval(doc,"//select[@name='vprod']")[0].selectedIndex;
        var qm = event.target.parentNode.getAttribute("id").match(/[0-9]+/);
        var arbeiter = Math.floor(qm / 10);
    }


    if (zeit.search(":") < 0) {
        var prodZeit = zeit * 60;
    } else {
        zeit = zeit.split(":");
        if (zeit.length == 2) {
            var prodZeit = zeit[0] * 60 * 60 + zeit[1] * 60;
        } else  var prodZeit = zeit[0] * 24 * 60 * 60 + zeit[1] * 60 * 60 + zeit[2] * 60;
    }


    var prodProStd = 3600/(2400/prodPref[produkt]*(1 - (ofaktor * Math.floor(qm/4000)))*(0.5+100/arbeiter));

    var menge = Math.floor(prodProStd * prodZeit / 3600);

    kl_eval(doc,"//input[@name='vanz']")[0].value = menge;

}

function kl_inputCalc(event){

    var input = event.target.value;

    var zahl;

    while(zahl = input.match(/[0-9.,]+k/)){

        input = input.replace(zahl, zahl.toString().replace(",",".").replace("k","") * 1000);

    }

    while(zahl = input.match(/[0-9.,]+m/)){

        input = input.replace(zahl, zahl.toString().replace(",",".").replace("m","") * 1000000);

    }

    if (input.search(";") > -1){

        input = input.replace(/[;]/g,"");
        input = input.replace(/[,]/g,".");

        var ergebnis = 0;

        try{

            eval("ergebnis ="+input);

        }catch(e){

            ergebnis = "error";

        }

        input = ergebnis;



    }

    event.target.value = input;


}

////////////////////////////////
// Programm Code
////////////////////////////////
function kl_init() {
    window.addEventListener("DOMContentLoaded", kl_appLoad, true);
}
//kaufs
//gebs
//forschs

function kl_appLoad(event) {
    //start = new Date();
    var doc = event.originalTarget;
    docloc = doc.location.href;
    // Variablen Deklaration



    //show news


    if (kl_isKapilandDomain(doc.location)) {


        if (doc.location.href == "http://kapiland.de/" || doc.location.href == "http://www.kapiland.de/" || doc.location.href == "http://kapilands.com/" || doc.location.href == "http://www.kapiland.com/" || doc.location.href == "http://www.kapilands.nl/" || doc.location.href == "http://www.kapilands.fr/"){



            form = kl_eval(doc, "//div/form")[0];

            link = doc.createElement("A");

            link.innerHTML = "<font style='font-weight: bold; cursor: pointer;'>KapiSkript News</font>";

            form.appendChild(doc.createElement("BR"));
            form.appendChild(link);



            inhalt = "";
            inhalt += "<h2>KapiSkript braucht DICH!</h2>Da ich, RaNaN, leider nicht mehr aktiv am KapiSkript weiterarbeiten kann, suche ich neue Teammitglieder!!<br><br>";
            inhalt += "Das KapiSkript ist komplett OpenSource und jeder der möchte kann daran mitarbeiten. Vorallem wird ein neuer JS Entwickler gesucht.<br><br>";
            inhalt += "Leider wurde der Support im kapiforum eingestellt, aber ihr bekommt auf der neuen Projektseite alle nötigen Infos und könnt über alle Themen diskutieren ohne eine Zensur fürchten zu müssen.<br><br>";
            inhalt += "Links: <a target='_blank' href='http://code.google.com/p/kapiskript/'>Projektseite</a>  <a target='_blank' href='http://groups.google.com/group/kapiskript'>Diskussion</a><br><br><h2>KapiSkript needs YOU!</h2>";
            inhalt += "We are looking for new developers, due to I can not effort enough time to maintime the KapiSkript.<br><br>Check out the new projectsites for discussion and infos.<br><br>Links: <a target='_blank' href='http://code.google.com/p/kapiskript/'>Projectpage</a>";
            inhalt += "<a target='_blank' href='http://groups.google.com/group/kapiskript'>Discussion</a><br><br><br><a style='cursor: pointer;' id='klNewsclose'>schlie&szlig;en | close</a>";



            var div = NeuesElement(doc,"div", inhalt,"style","background-color: white; left: 30px; position: absolute; z-index: 1000; width: 250px; height: 510px; top: 160px;display: none;border: 2px solid; padding:5px;font-size: 11.5px;", "id", "klNews");


            doc.body.appendChild(div);

           doc.getElementById("klNewsclose").addEventListener("click", function(e){

                doc.getElementById("klNews").style.display = "none";
                kl_prefManager.setBoolPref("extensions.ks.news", false);

            }, true)


            link.addEventListener("click", function(e){

                doc.getElementById("klNews").style.display = "block";

            }, true)


            if (kl_prefManager.getBoolPref("extensions.ks.news")){

                div.style.display = "block";

            }

        }

        if (kl_prefManager.getBoolPref("extensions.ks.inputcalc")){

            var inputs = kl_eval(doc,"//input[@type='text']");

            for(var i =0; i < inputs.length;i++){

                inputs[i].addEventListener("keyup", kl_inputCalc, true);

            }

        }


        if (doc.location.href.search(/page=(kaufs|gebs|forschs|sonst)(&|$)/) > -1) {

            try{
                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                var mainTB = kl_eval(doc,"//td[@width='26%']/../..")[0];

                if (doc.location.href.search(/page=kaufs(&|$)/) > -1) cn = 2;
                else cn = 1;

                if (kl_prefManager.getIntPref("extensions.ks.geb2sort") > 0) {
                    //////// Gebäudesortierung
                    var gebs = new Array();
                    letzte = "";
                    k = -1;

                    for (i = 1;mainTB.childNodes.length != 1; i++) {
                        typ = mainTB.childNodes[1].childNodes[cn].textContent.match(x_name)[1];
                        if (typ == letzte) {
                            gebs[k].push(mainTB.childNodes[1].cloneNode(true));
                            mainTB.removeChild(mainTB.childNodes[1]);
                        }
                        else {
                            k++;
                            gebs.push(new Array());
                            gebs[k].push(mainTB.childNodes[1].cloneNode(true));
                            mainTB.removeChild(mainTB.childNodes[1]);
                        }
                        letzte = typ;
                    }
                    for (i = 0; i < gebs.length; i++) {
                        if (kl_prefManager.getIntPref("extensions.ks.geb2sort") == 1) gebs[i].sort(sortBereit);
                        else gebs[i].sort(sortSize);
                    }

                    for (k = 0; k < gebs.length; k++) {
                        for (i = 0; i < gebs[k].length; i++) {
                            mainTB.appendChild(gebs[k][i]);
                        }
                    }

                    var w = 0;
                    for (i = 1; i < mainTB.childNodes.length; i++) {

                        if (w == 0) {
                            for (k = 0; k < mainTB.childNodes[i].childNodes.length; k++) {
                                if (mainTB.childNodes[i].childNodes[k].nodeName != "#text") {
                                    mainTB.childNodes[i].childNodes[k].setAttribute("class", "white");
                                }
                            }
                            w = 1;
                        } else {
                            for (k = 0; k < mainTB.childNodes[i].childNodes.length; k++) {
                                if (mainTB.childNodes[i].childNodes[k].nodeName != "#text") {
                                    mainTB.childNodes[i].childNodes[k].setAttribute("class", "white2");
                                }
                            }
                            w = 0;
                        }
                    }
                }

                if (kl_prefManager.getBoolPref("extensions.ks.gebover")) {
                    /////// Gebäudeübersicht
                    var letzte = "";
                    var uebers = Array();
                    j = 0;
                    for (i = 1; i < mainTB.childNodes.length; i++) {
                        var typ = mainTB.childNodes[i].childNodes[cn].textContent.match(x_name)[1];
                        if (letzte != typ) {
                            var ueberschrift = doc.createElement("TR");
                            mainTB.childNodes[i].parentNode.insertBefore(ueberschrift, mainTB.childNodes[i]);
                            ueberschrift.id = "ksm";
                            ueberschrift.className = "menue";
                            ueberschrift.innerHTML = "<td class=\"white\" style=\"border-top: 1px groove;\" colspan=\"4\"><b>" + typ + "</b><a name=\"" + typ + "\">&nbsp;</a> <a href=\"#top\">("+loca[lang]["nachoben"]+")</a></td>";
                            letzte = typ;
                            uebers[j] = typ;
                            j++;
                        }
                    }
                    var qs = "";
                    for (j = 0; j < uebers.length; j++) {
                        qs = qs + "<a href=\"#" + uebers[j] + "\">" + uebers[j] + "</a>&nbsp; ";
                    }
                    var topic = doc.createElement("TR");
                    var topicTD = doc.createElement("TD");
                    topicTD.setAttribute("colspan", "4");
                    topicTD.innerHTML = loca[lang]["gehezu"] + qs + "<hr>";
                    topic.appendChild(topicTD);
                    mainTB.insertBefore(topic, mainTB.firstChild);
                }

                // Endzeit einfügen in Gebäude,Verkauf,Forschung, Spezial
                if (kl_prefManager.getBoolPref("extensions.ks.endzeit")) {
                    var Wochentag = loca[lang]["wochentag"];
                    var first_row = kl_prefManager.getBoolPref("extensions.ks.gebover")?2:1;
                    //one row more if gebover-links are inserted
                    for (i = first_row; i < mainTB.childNodes.length; i++){
                        if (mainTB.childNodes[i].lastChild.firstChild.textContent.search(loca[lang]["bereit"]) == -1 && mainTB.childNodes[i].getAttribute("id") != "ksm" && mainTB.childNodes[i].lastChild.firstChild.textContent != loca[lang]["keinverkauf"]) {
                            TRstatus = mainTB.childNodes[i].lastChild;
                            var el = TRstatus.firstChild;
                            var zeitAlt = TRstatus.textContent;
                            var zeit = zeitAlt.split(":");
                            var stunden = parseFloat(zeit[0]);


                            zeiten = kl_prefManager.getCharPref("extensions.ks.zeiten");
                            zeiten = zeiten.split(":");

                            farben = kl_prefManager.getCharPref("extensions.ks.farben");
                            farben = farben.split(":");


                            //noinspection JSUnusedLocalSymbols
                            try {
                                if (stunden < parseFloat(zeiten[1])) {
                                    el.setAttribute('style', 'color: ' + farben[1] + ';font-weight: bold;');
                                } else if (stunden < parseFloat(zeiten[2])) {
                                    el.setAttribute('style', 'color: ' + farben[2] + ';font-weight: bold;');
                                } else if (stunden < parseFloat(zeiten[3])) {
                                    el.setAttribute('style', 'color: ' + farben[3] + ';font-weight:bold;');
                                }

                            } catch(e) {
                            }

                            var ms = zeit[0] * 60 * 60 * 1000 + zeit[1] * 60 * 1000 + zeit[2] * 1000;
                            var FertigZeit = new Date();
                            FertigZeit.setTime(FertigZeit.getTime() + ms);

                            if (stunden < 24) {
                                TRstatus.appendChild(doc.createTextNode("\n" + (((FertigZeit.getHours() < 10) ? "0" : "") + FertigZeit.getHours()) + ":" + (((FertigZeit.getMinutes() < 10) ? "0" : "") + FertigZeit.getMinutes()) + unescape("%A0"+loca[lang]["uhr"])));
                            } else if (stunden < 48) {
                                //noinspection JSDeprecatedSymbols
                                TRstatus.appendChild(doc.createTextNode("\n" + Wochentag[FertigZeit.getDay()] + " " +
                                    ((FertigZeit.getDate() < 10) ? "0" + FertigZeit.getDate() : FertigZeit.getDate())
                                    + "." + (((parseFloat(FertigZeit.getMonth()) + 1) < 10) ? "0" + (parseFloat(FertigZeit.getMonth()) + 1) : (parseFloat(FertigZeit.getMonth()) + 1))
                                    + " " + ((FertigZeit.getHours() < 10) ? "0" + FertigZeit.getHours() : FertigZeit.getHours()) + ":" + ((FertigZeit.getMinutes() < 10) ? "0" + FertigZeit.getMinutes() : FertigZeit.getMinutes()) + unescape("%A0"+loca[lang]["uhr"])));
                            } else {
                                TRstatus.appendChild(doc.createTextNode("\n" + Wochentag[FertigZeit.getDay()] + " " + ((FertigZeit.getDate() < 10) ? "0" + FertigZeit.getDate() : FertigZeit.getDate())
                                    + "." + (((parseFloat(FertigZeit.getMonth()) + 1) < 10) ? "0" + (parseFloat(FertigZeit.getMonth()) + 1) : (parseFloat(FertigZeit.getMonth()) + 1))));
                            }

                        }
                        }
                }
                // ges produktion
                if (kl_prefManager.getBoolPref("extensions.ks.prodanz") && doc.location.href.search(/page=gebs(&|$)/) > -1){
                    try{
                        var tb = kl_eval(doc,"//table/tbody/tr[3]/td/table/tbody/tr/td[1]/table/tbody")[0]; //unsauber?!?
                        var produkte = kl_evalNode(doc,mainTB,".//tr/td[3]");

                        var produkt = new Array();
                        var exist = false;
                        var pexist = false;
                        var p = -1;
                        var q = -1;
                        var lq,lp;


                        var menge, name, quali;


                        for(i=0;i < produkte.length;i++){

                            if (produkte[i].textContent.search(/^(\d+) (\S+) .*?(\d+)/) == -1) continue;
                            menge = RegExp.$1 * 1;
                            name = RegExp.$2;
                            quali = RegExp.$3;

                            if (name != lp){
                                for(var n=0;n < produkt.length;n++){
                                    if (produkt[n][0] == name){
                                        p = n;
                                        pexist = true;
                                        break;
                                    }
                                }
                                if (!pexist){
                                    p = produkt.length;
                                    produkt.push(new Array(name));
                                }else pexist = false;

                                q = 0;
                                lq = "undef";
                            }
                            if (quali != lq){
                                for(var k=1;k < produkt[p].length;k+=2){
                                    if (produkt[p][k] == quali){
                                        q = k + 1;
                                        exist = true;
                                        break;
                                    }
                                }
                                if (!exist){
                                    produkt[p].push(quali);
                                    produkt[p].push(0);
                                    q += 2;
                                }else exist = false;
                            }
                            produkt[p][q] += menge;

                            lp = name;
                            lq = quali;

                        }

                        var tr = doc.createElement("tr");
                        var td = NeuesElement(doc,"TD","","class","white2");
                        td.appendChild(NeuesElement(doc,"FONT",loca[lang]["prod"],"class","Gross"));
                        td.appendChild(doc.createElement("BR"));
                        td.appendChild(doc.createElement("BR"));


                        for(i=0;i < produkt.length;i++){
                            var gesamt = 0;
                            for(k=1;k<produkt[i].length-1;k+=2){
                                gesamt += produkt[i][k+1];
                            }
                            td.appendChild(NeuesElement(doc,"FONT",produkt[i][0]+": "+Math.setSectionPoints(gesamt),"style","font-weight: bold;"));
                            td.appendChild(doc.createElement("BR"));

                            for(k=1;k<produkt[i].length-1;k+=2){
                                td.appendChild(NeuesElement(doc,"FONT","(Q:"+produkt[i][k]+") "+ Math.setSectionPoints(produkt[i][k+1]),"style","padding-left: 10px;"));
                                td.appendChild(doc.createElement("BR"));

                            }
                        }

                        td.appendChild(doc.createElement("BR"));
                        tr.appendChild(td);
                        EinfuegenHinter(tr,tb.childNodes[1]);

                    }catch(e){}
                    }
                // Countdown
                if (kl_prefManager.getBoolPref("extensions.ks.countdown")) {
                    var cd = 0;

                    for (i = 1; i < mainTB.childNodes.length; i++) {
                        if (mainTB.childNodes[i].lastChild.firstChild.textContent.search(loca[lang]["bereit"]) == -1 && mainTB.childNodes[i].getAttribute("id") != "ksm" && mainTB.childNodes[i].lastChild.firstChild.textContent != loca[lang]["keinverkauf"]) {
                            //noinspection JSUnusedLocalSymbols
                            try {
                                mainTB.childNodes[i].lastChild.firstChild.setAttribute("id", "cd" + cd);
                                cd++;
                            } catch(e) {
                            }
                        }
                    }
                    zeiten = kl_prefManager.getCharPref("extensions.ks.zeiten");
                    zeiten = zeiten.split(":");

                    farben = kl_prefManager.getCharPref("extensions.ks.farben");
                    farben = farben.split(":");
                    /* // Alter Countdown
                doc.body.firstChild.appendChild(NeuesElement(doc, "SCRIPT", "function countdown(){var cd=" + cd + ";for(var i= 0;i < cd;i++){var el = document.getElementById('cd'+i);var zeit = el.textContent;var zeit = zeit.split(':');var stunden = parseFloat(zeit[0]);var minuten = parseFloat(zeit[1]);var sekunden = parseFloat(zeit[2]);if (sekunden == 0){if (minuten == 0){if (stunden == 0){}else{stunden--;minuten=59;sekunden=59;}}else{minuten--;sekunden = 59;}}else{sekunden--;}zeit=stunden+':'+((minuten < 10) ? '0' + minuten : minuten)+':'+((sekunden < 10) ? '0' + sekunden : sekunden);el.textContent = zeit;if (stunden == 0 && minuten < " + zeiten[0] + "){el.setAttribute('style','color: " + farben[0] + ";font-weight: bold;');}else if (stunden < " + zeiten[1] + "){el.setAttribute('style','color: " + farben[1] + ";font-weight: bold;');}else if (stunden < " + zeiten[2] + "){el.setAttribute('style','color: " + farben[2] + ";font-weight: bold;');}else if (stunden < " + zeiten[3] + "){el.setAttribute('style','color: " + farben[3] + ";font-weight:bold;');};}; window.setTimeout(countdown, 1000);}", "language", "JavaScript"));
                     */


                    doc.getElementsByTagName("head")[0].appendChild(NeuesElement(doc, "SCRIPT", "var el;var sekunden = new Array();function kl_evalNode(doc,aNode,aExpr){var result = doc.evaluate(aExpr,aNode,null,0, null);var found = [];var res;while (res = result.iterateNext())found.push(res);return found;}function countdown(){for(var i=0; i<el.length; i++){if ( sekunden[i] < 0 ){el[i].textContent= '--:--:--';}else{var sek = sekunden[i];var stunden = Math.floor(sek/3600);sek = sek - stunden*3600;var minuten = Math.floor(sek/60);sek = sek - minuten*60;el[i].textContent = stunden+':'+((minuten < 10) ? '0' + minuten : minuten)+':'+((sek < 10) ? '0' + sek : sek);if (stunden == 0 && minuten < " + zeiten[0] + "){el[i].setAttribute('style','color: " + farben[0] + ";font-weight: bold;');}else if (stunden < " + zeiten[1] + "){el[i].setAttribute('style','color: " + farben[1] + ";font-weight: bold;');}else if (stunden < " + zeiten[2] + "){el[i].setAttribute('style','color: " + farben[2] + ";font-weight: bold;');}else if (stunden < " + zeiten[3] + "){el[i].setAttribute('style','color: " + farben[3] + ";font-weight:bold;');}}sekunden[i] = sekunden[i]-1;}window.setTimeout(countdown, 1000);}function init(){el = kl_evalNode(document,document,\"//a[contains(@id,'cd')]\");var wert = '';for (var i=0; i < el.length; ++i){wert = el[i].textContent;var splitted = new Array();splitted = wert.split(':');sekunden.push(splitted[0]*3600+splitted[1]*60+splitted[2]*1);}countdown();}", "language", "JavaScript"));

                    doc.body.setAttribute("onload", "init();");
                }

                if (kl_prefManager.getBoolPref("extensions.ks.gebfast")) {
                    for (i = 1; i < mainTB.childNodes.length; i++) {
                        var TRstatus = mainTB.childNodes[i].lastChild;
                        TRstatus.firstChild.setAttribute("oncontextmenu", "return false;");
                        TRstatus.firstChild.addEventListener("mouseup", kl_fastAccess, true);
                    }
                    doc.addEventListener("click", function(e) {
                        if (e.button == 0)clr();
                    }, true);
                }
            }catch(e){
                throw e; // Debugging
            }
        } else if (doc.location.href.search("page=roh&art=") > -1) {

            doc.addEventListener("mousemove", mouseMove, true);

            doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

            if (kl_prefManager.getBoolPref("extensions.ks.produktion")) {
                if(kl_isWelt5(doc.location)) {
                    var produkt = doc.getElementById("SPAN_PRODUKT_PRODUZIEREN_PLATZHALTER");

                    var info = doc.createTextNode(loca[lang]["prodzeit"]);
                    Input = NeuesElement(doc, "INPUT", "", "maxlength", "8", "value", "DD:HH:MM", "size", "8");

                    EinfuegenHinter(info, produkt);
                    EinfuegenHinter(Input, info);
                    Input.addEventListener("focus", empty, true);
                    Input.addEventListener("keyup", kl_BerechneProduktion, true);
                    Input.addEventListener("change", kl_BerechneProduktion, true);
                } else {
                    mainForm = kl_eval(doc,"//td/form[not(@id='kss')]");
                    //mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.parentNode.nodeName == 'TD' && Kn.getAttribute('id') != 'kss');"));


                    mainTB = mainForm[0].firstChild.firstChild;

                    var inputs = new Array();
                    for (i = 1; i < mainTB.childNodes.length; i++) {
                        inputs[i] = mainTB.childNodes[i].lastChild.firstChild;

                        if (inputs[i].nodeName != "INPUT") continue;

                        inputs[i].parentNode.appendChild(doc.createTextNode(loca[lang]["endzeit"]));
                        inputs[i].addEventListener("keyup", kl_BerechneProdZeit, true);
                        inputs[i].addEventListener("keyup", kl_ProdKosten, true);
                        inputs[i].addEventListener("change", clr, true);

                        var Produkt = mainTB.childNodes[i].firstChild.lastChild.firstChild
                            .firstChild.firstChild.firstChild;

                        var info = doc.createTextNode(loca[lang]["prodzeit"]);
                        Input = NeuesElement(doc, "INPUT", "", "maxlength", "8", "value", "DD:HH:MM", "size", "8");

                        EinfuegenHinter(info, Produkt.nextSibling);
                        EinfuegenHinter(Input, info);
                        Input.addEventListener("focus", empty, true);
                        Input.addEventListener("keyup", kl_BerechneProduktion, true);
                        Input.addEventListener("keyup", kl_BerechneProdZeit, true);
                        Input.addEventListener("keyup", kl_ProdKosten, true);
                        Input.addEventListener("change", clr, true);
                        Input.addEventListener("change", kl_BerechneProduktion, true);

                    }
                }
            }
        } else if ((doc.location.href.search(/page=roh2(&|$)/) > -1) || (doc.location.href.search(/page=verw_p2(&|$)/) > -1)) {
            if (kl_prefManager.getBoolPref("extensions.ks.spqchoose") && (doc.body.textContent.search(loca[lang]["waehlrohstoff"]) > -1)) {

                var mTB = kl_eval(doc,"//form[@name='timeform' and not(@id='kss')]")[0].getElementsByTagName("TABLE")[0].firstChild;

                //var mTB = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.getAttribute('name') == 'timeform' && Kn.getAttribute('id') != 'kss');"))[0].getElementsByTagName("TABLE")[0].firstChild;

                var prods = new Array();
                letzte = "";
                k = -1;

                for (i = 0;mTB.childNodes.length != 0; i++) {
                    typ = mTB.childNodes[0].firstChild.textContent.match(x_quali)[1];
                    if (typ == letzte) {
                        prods[k].push(mTB.childNodes[0].cloneNode(true));
                        mTB.removeChild(mTB.childNodes[0]);
                    }
                    else {
                        k++;
                        prods.push(new Array());
                        prods[k].push(mTB.childNodes[0].cloneNode(true));
                        mTB.removeChild(mTB.childNodes[0]);
                    }
                    letzte = typ;
                }
                for (i = 0; i < prods.length; i++) {
                    prods[i].sort(sortProd);
                    for(k=0;k < prods[i][0].childNodes.length;k++){
                        prods[i][0].childNodes[k].setAttribute("style","border-top: 1px groove;");
                    }
                    prods[i][0].lastChild.lastChild.setAttribute("checked","true");

                    for(k=0;k < prods[i].length;k++){
                        prods[i][k].lastChild.lastChild.setAttribute("id","p"+i+"q"+k);
                        prods[i][k].addEventListener("click", kl_supportChoose, true);
                        prods[i][k].addEventListener("change", kl_supportChoose, true);
                    }
                }

                for (k = 0; k < prods.length; k++) {
                    for (i = 0; i < prods[k].length; i++) {
                        mTB.appendChild(prods[k][i]);
                    }
                }

                var w = 0;
                for (i = 0; i < mTB.childNodes.length; i++) {

                    if (w == 0) {
                        for (k = 0; k < mTB.childNodes[i].childNodes.length; k++) {
                            if (mTB.childNodes[i].childNodes[k].nodeName != "#text") {
                                mTB.childNodes[i].childNodes[k].setAttribute("class", "white");
                            }
                        }
                        w = 1;
                    } else {
                        for (k = 0; k < mTB.childNodes[i].childNodes.length; k++) {
                            if (mTB.childNodes[i].childNodes[k].nodeName != "#text") {
                                mTB.childNodes[i].childNodes[k].setAttribute("class", "white2");
                            }
                        }
                        w = 0;
                    }
                }

            }

            if (kl_prefManager.getBoolPref("extensions.ks.prodskip") && doc.body.textContent.search(loca[lang]["ngenug"]) == -1 && doc.body.textContent.search(loca[lang]["waehlrohstoff"]) == -1 && (doc.location.href.search(/page=roh2(&|$)/) > -1)) {
                loc = "http://" + doc.location.host + doc.location.pathname + "?" + "page=gebs&UIN=" + extract(doc.location.search, "UIN=", "&") + "&show=all";
                gBrowser.selectedBrowser.contentDocument.location.replace(loc);
            }


        }
        else if (doc.location.href.search("page=markt3") > -1 && doc.location.href.search("filled=1") == -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.ausgabenmarkt")) {
                mainForm = kl_eval(doc,"//td/form[not(@id='kss')]");
                //mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.parentNode.nodeName == 'TD' && Kn.getAttribute('id') != 'kss');"));

                Input = mainForm[0].childNodes[3];


                EinfuegenHinter(NeuesElement(doc, "font", "", "id", "gesamtkosten"), mainForm[0].nextSibling);

                anzahl = Input.value;
                var td = Input.parentNode.parentNode;
                var preis = td.textContent.match(loca[lang]["zumpreisvon"])[2];

                kosten = preis * anzahl;

                kosten = Math.round(kosten * 100) / 100;

                kosten = Math.setSectionPoints(kosten);

                doc.getElementById("gesamtkosten").textContent = loca[lang]["gesamtkosten"] + kosten + " "+loca[lang]["c"];

                Input.addEventListener("keyup", kl_BerechneKosten, true);
            }
        } else if (doc.location.href.search("page=kauf5") > -1) {
            mainTable = kl_eval(doc,"//td/form/table");
            //mainTable = FindeTags(doc, "TABLE", new Function("Kn", "return (Kn.parentNode.nodeName == 'FORM' && Kn.parentNode.parentNode.nodeName == 'TD');"));
            mainTB = mainTable[0].firstChild;

            if (lang == "de"){
                var w = extract(docloc,"welt","-kapiland");
                var l = extract(docloc,"&x=","&");

                if (kl_prefManager.getBoolPref("extensions.ks.statsverkaufcol")){
                    kl_verkstatreq(mainTB,w,l);
                    mainTB.firstChild.firstChild.appendChild(NeuesElement(doc,"img","","height","12","src","chrome://kapiland/skin/loading.gif","id","ksloadingbar","style","vertical-align: middle;"));
                }
                if (kl_prefManager.getBoolPref("extensions.ks.grphverk")) {
                    if (kl_prefManager.getBoolPref("extensions.ks.grphaut")){
                        var m1 = "angebot";
                        var m2 = "nachfrage";
                    }else{
                        switch(kl_prefManager.getIntPref("extensions.ks.grph1")){
                            case 0:
                                var m1 = "angebot";
                                break;
                            case 1:
                                var m1 = "nachfrage";
                                break;
                            case 2:
                                var m1 = "preis";
                                break;
                            case 3:
                                var m1 = "quali";
                                break;
                        }
                        switch(kl_prefManager.getIntPref("extensions.ks.grph2")){
                            case 0:
                                var m2 = "angebot";
                                break;
                            case 1:
                                var m2 = "nachfrage";
                                break;
                            case 2:
                                var m2 = "preis";
                                break;
                            case 3:
                                var m2 = "quali";
                                break;
                            case 4:
                                var m2 = "null";
                                break;
                        }
                    }
                    for (i = 1; i < mainTB.childNodes.length; i++) {
                        try{
                            mainTB.childNodes[i].firstChild.innerHTML += " <a style='cursor: pointer' href='http://stats.kapigeco.de/graph.php?w="+w+"&l="+l+"&m1="+m1+"&m2="+m2+"&p="+unescape(mainTB.childNodes[i].firstChild.textContent.match(/[ ]([a-zA-ZäöüÄÜÖß]*)/)[1])+"' target='_blank'><img border='0' src='chrome://kapiland/skin/graph.png' width='22' height='13' style='vertical-align: middle'></img></a>";
                        }catch(e){
                            continue;
                        }
                    }
                    }
                }
            if (kl_prefManager.getBoolPref("extensions.ks.alleverk")){
                for (i = 1; i < mainTB.childNodes.length; i++) {
                    try{
                        var alles = NeuesElement(doc,"A",loca[lang]["alles"],"class","klein","style","padding-left: 5px;cursor: pointer;");
                        alles.addEventListener("click", kl_alles, true);
                        mainTB.childNodes[i].firstChild.appendChild(alles);
                    }catch(e){
                        continue;
                    }
                    }
            }
            if (kl_prefManager.getBoolPref("extensions.ks.umsatzverkauf")) {

                for (i = 1; i < mainTB.childNodes.length; i++) {
                    try{
                        mainTB.childNodes[i].lastChild.firstChild.addEventListener("keyup", kl_BerechneUmsatz, true);
                    }catch(e){
                        break;
                    }
                }

                Input = mainTable[0].parentNode.lastChild.childNodes[1];
                Input.setAttribute("id", "preis");

                Input.addEventListener("keyup", kl_BerechneUmsatz, true);

                EinfuegenHinter(NeuesElement(doc, "font", loca[lang]["gewinnproz"]), mainTable[0].parentNode.lastChild);

                EinfuegenHinter(NeuesElement(doc, "INPUT", "", "maxlength", "6", "value", loca[lang]["gewinn"], "size", "6", "id", "gewinn"), mainTable[0].parentNode.lastChild);
                doc.getElementById("gewinn").addEventListener("keyup", kl_berechneGewinn, true);
                doc.getElementById("gewinn").addEventListener("focus", empty, true);

                EinfuegenHinter(NeuesElement(doc, "font", "", "id", "umsatz"), mainTable[0].parentNode.lastChild);
                doc.getElementById("umsatz").textContent = loca[lang]["umsatz"]+" "+loca[lang]["gewinn"]+":"+loca[lang]["gewinnps"];
                Input.parentNode.parentNode.parentNode.removeChild(Input.parentNode.parentNode.parentNode.lastChild);


            }
        } else if (doc.location.href.search(/page=lager(&|$)/) > -1) {
            var prodInputs = kl_eval(doc,"//input[@name='p_anz[]']");
            //var prodInputs = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'p_anz[]');"));

            if (kl_prefManager.getBoolPref("extensions.ks.allewaren")) {
                for (i = 0; i < prodInputs.length; i++) {
                    prodInputs[i].parentNode.appendChild(doc.createElement("BR"));
                    var allewaren = new Array();
                    allewaren[i] = NeuesElement(doc, "A", loca[lang]["alles"], "style", "cursor: pointer;");
                    allewaren[i].addEventListener("click", kl_alleWaren, true);
                    prodInputs[i].parentNode.appendChild(allewaren[i]);
                }
            }

            if (kl_prefManager.getBoolPref("extensions.ks.umsatzlager")) {

                for (i = 0; i < prodInputs.length; i++) {
                    prodInputs[i].addEventListener("keyup", kl_lager, true);
                }

                var marktPreis = kl_eval(doc,"//input[@name='wbet']");

                //var marktPreis = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'wbet');"));
                marktPreis[0].addEventListener("keyup", kl_lager, true);

                var vertragPreis = kl_eval(doc,"//input[@name='vbet']");
                //var vertragPreis = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'vbet');"));
                vertragPreis[0].addEventListener("keyup", kl_lager, true);

                EinfuegenHinter(NeuesElement(doc, "font", "", "id", "gewinn"), marktPreis[0].parentNode.parentNode.parentNode.parentNode);
                doc.getElementById("gewinn").textContent = loca[lang]["umsatz"]+" "+loca[lang]["gewinn"]+":"+loca[lang]["gewinnps"];
            }

            if (kl_prefManager.getBoolPref("extensions.ks.gesamtwert")) {

                var produkt = new Array();
                preis = new Array();

                for (i = 0; i < prodInputs.length; i++) {

                    produkt[i] = kl_int(prodInputs[i].parentNode.parentNode.firstChild.lastChild.textContent);
                    produkt[i] = produkt[i].replace(/\s/, "");

                    preis[i] = prodInputs[i].parentNode.parentNode.childNodes[3].textContent;
                    preis[i] = preis[i].replace(/\s/, "");
                    preis[i] = kl_int(preis[i]);
                    preis[i] = preis[i].replace(loca[lang]["c"], "");

                }

                var summe = 0;

                for (i = 0; i < produkt.length; i++) {

                    summe = summe * 1 + (produkt[i] * preis[i]);
                    summe = Math.round(summe * 100) / 100;
                }
                EinfuegenHinter(NeuesElement(doc, "font", loca[lang]["geswarenw"] + Math.setSectionPoints(summe) + loca[lang]["c"], "align", "right"), prodInputs[0].parentNode.parentNode.parentNode.parentNode);


            }
        } else if (doc.location.href.search(/page=(roh|forschen|kauf|oeffent|spez)7(&|$)/) > -1)
        {
            if (kl_prefManager.getBoolPref("extensions.ks.ausbau")) {

                var Input = kl_eval(doc,"//input[@name='ausbau']");

                //var Input = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('name') == 'ausbau');"));

                Input[0].addEventListener("keyup", kl_ausbau, true);

                var table = Input[0].parentNode.parentNode.parentNode.parentNode;
                var kosten = NeuesElement(doc, "font", loca[lang]["kosten"] + unescape("%A0%A0") + loca[lang]["dauer"], "id", "kosten");
                var kosten2 = NeuesElement(doc, "font", loca[lang]["steine"]+":" + unescape("%A0%A0") + loca[lang]["stahl"]+":" + unescape("%A0%A0") + loca[lang]["holz"]+":", "id", "kosten2");
                EinfuegenHinter(kosten2, table);
                EinfuegenHinter(doc.createElement("BR"), table);
                EinfuegenHinter(kosten, table);
            }
        } else if (doc.location.href.search(/page=vertrag(&|$)/) > -1)
        {
            var vertraege = kl_eval(doc,"//a[contains(@href,'page=vertrag2')]/../..");

            if (kl_prefManager.getBoolPref("extensions.ks.igmvertrag")){

                doc.body.lastChild.addEventListener("click", function(e) {
                    if (e.button == 0)clr();
                }, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));
                over = doc.getElementById("klDiv");


                var img;
                for(i =0;i < vertraege.length;i++){

                    img = NeuesElement(doc,"img","","src","chrome://kapiland/skin/igm.png","style","height: 12px; padding-left: 2px; padding-right: 2px; cursor: pointer;");

                    img.addEventListener("click",kl_igmPopup,true);
                    vertraege[i].lastChild.firstChild.textContent = vertraege[i].lastChild.firstChild.textContent.match(/. (.+)/)[1];
                    vertraege[i].lastChild.insertBefore(img,vertraege[i].lastChild.firstChild);
                }



            }
            if (kl_prefManager.getBoolPref("extensions.ks.schnellzugriff")) {
                //var vertraege = FindeTags(doc, "TR", new Function("Kn", "return (Kn.getAttribute('onmouseout') == 'clr()');"));

                for (i = 0; i < vertraege.length; i++)
                {
                    var url = vertraege[i].childNodes[1].firstChild.getAttribute("href");

                    if (check(vertraege[i].childNodes[1].firstChild.textContent, loca[lang]["gebsnamen"])) {
                        anurl = url.replace("vertrag2", "vertrag9");
                        aburl = url.replace("vertrag2", "vertrag10");
                    } else if (vertraege[i].childNodes[1].firstChild.textContent.search(loca[lang]["tech"]) > -1) {
                        anurl = url.replace("vertrag2", "vertrag12");
                        aburl = url.replace("vertrag2", "vertrag11");
                    } else if (vertraege[i].childNodes[1].firstChild.textContent.search("Coins") > -1) {
                        anurl = url.replace("vertrag2", "vertrag14");
                        aburl = url.replace("vertrag2", "vertrag13");
                    } else {
                        anurl = url.replace("vertrag2", "vertrag3");
                        aburl = url.replace("vertrag2", "vertrag4");
                    }

                    var annehmen = NeuesElement(doc, "A", loca[lang]["annehmen"], "href", anurl, "style", "padding-left: 20px; padding-right: 5px");
                    var ablehnen = NeuesElement(doc, "A", loca[lang]["ablehnen"], "href", aburl, "style", "padding-left: 5px");

                    vertraege[i].childNodes[1].appendChild(annehmen);
                    vertraege[i].childNodes[1].appendChild(doc.createTextNode("|"));
                    vertraege[i].childNodes[1].appendChild(ablehnen);

                }
            }
            if (kl_prefManager.getBoolPref("extensions.ks.sortvertrag")){
                var tb = vertraege[0].parentNode;
                var vert = new Array();
                for(i = 0; tb.childNodes.length != 0;i++){
                    vert.push(tb.removeChild(tb.childNodes[0]));
                }
                vert.sort(sortVertrag);

                for(i =0;i < vert.length;i++){
                    tb.appendChild(vert[i]);
                }
            }

        } // ----------Skip Pages-------------
        else if (doc.location.href.search(/vertrag(3|4|5|9|10|11|12|13|14)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.vertragskip") && doc.body.textContent.search(loca[lang]["ngenuggeld"]) == -1) {
                loc = doc.location.href;
                loc = loc.substring(0, loc.search("&nr="));
                loc = loc.replace(/vertrag[0-9]*/, "vertrag");
                gBrowser.selectedBrowser.contentDocument.location.replace(loc);
            }
        } else if (doc.location.href.search(/page=markt3(&|$)/) > -1 && doc.location.href.search("filled=1") > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.marktskip") && doc.body.textContent.search(loca[lang]["eswurden"]) > -1) {
                gBrowser.selectedBrowser.contentDocument.location.replace(window.content.history[window.content.history.length - 3]);
            }
        } else if (doc.location.href.search("page=adress_notizbuch") > -1)
        {
            var mainForm = kl_eval(doc,"//td/form[not(@id='kss')]");
            //var mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.parentNode.nodeName == 'TD' && Kn.getAttribute('id') != 'kss');"));

            if (kl_prefManager.getBoolPref("extensions.ks.sortadress")) {

                if (mainForm[0].firstChild.firstChild.getElementsByTagName("TH").length < 1 ){
                    var firmen = new Array();
                    for (i = 0;mainForm[0].firstChild.firstChild.childNodes.length > 1; i++)
                    {
                        firmen[i] = mainForm[0].firstChild.firstChild.childNodes[1].cloneNode(true);
                        mainForm[0].firstChild.firstChild.removeChild(mainForm[0].firstChild.firstChild.childNodes[1]);

                    }

                    firmen.sort(sortAdress);

                    for (i = 0; i < firmen.length; i++) {
                        mainForm[0].firstChild.firstChild.appendChild(firmen[i]);
                    }
                }else{ // Neues Notizbuch
                    var firmen = new Array();
                    var tb = mainForm[0].firstChild.firstChild;
                    for (i =0;tb.childNodes.length > 1;i++){
                        try{
                            firmen.push(new Array());
                            firmen[i].push(new Array());
                            firmen[i][0] = tb.childNodes[1].cloneNode(true);
                            firmen[i][1] = tb.childNodes[2].cloneNode(true);

                            tb.removeChild(tb.childNodes[1]);
                            tb.removeChild(tb.childNodes[1]);
                        }catch(e){
                            break;
                        }
                    }

                    firmen.sort(sortNeuAdress);

                    for(i=0;i < firmen.length;i++){

                        tb.appendChild(firmen[i][0]);
                        tb.appendChild(firmen[i][1]);

                    }

                }

            }

            if (kl_prefManager.getBoolPref("extensions.ks.igmadress")){


                doc.body.lastChild.addEventListener("click", function(e) {
                    if (e.button == 0)clr();
                }, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                over = doc.getElementById("klDiv");


                var tBody = mainForm[0].firstChild.firstChild;

                var igm;
                for (var i=1;i < tBody.childNodes.length;i++){

                    if (tBody.childNodes[i].firstChild.nodeName == "TH") continue;

                    img = NeuesElement(doc,"img","","src","chrome://kapiland/skin/igm.png","style","height: 13px; padding-left: 2px; padding-right: 2px; cursor: pointer;");

                    img.addEventListener("click",kl_igmPopup,true);

                    tBody.childNodes[i].childNodes[3].removeChild(tBody.childNodes[i].childNodes[3].firstChild);
                    tBody.childNodes[i].childNodes[3].appendChild(img);

                }

            }

        } else if (doc.location.href.search("page=nachricht4") > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.nachrichtskip")) {
                loc = doc.location.href;
                loc = loc.replace(/nachricht[0-9]*/, "nachricht");
                gBrowser.selectedBrowser.contentDocument.location.replace(loc);
            }
        } else if (doc.location.href.search(/page=nachricht3?(&|$)/) > -1) {
            var send = kl_eval(doc,"//input[@type='submit' and @class='send']")[0];
            //var send = FindeTags(doc, "INPUT", new Function("Kn", "return (Kn.getAttribute('type') == 'submit' && Kn.getAttribute('class') == 'send');"))[0];
            send.addEventListener("click",kl_signatur,true);


        } else if (doc.location.href.search(/page=forschen(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.forschend")) {
                var forschLinks = kl_eval(doc,"//a[contains(@href,'page=forschen2')]");
                //var forschLinks = FindeTags(doc, "A", new Function("Kn", "return (Kn.getAttribute('href').search('page=forschen2&') > -1);"));

                doc.addEventListener("mousemove", mouseMove, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                for (i = 0; i < forschLinks.length; i++) {

                    forschLinks[i].addEventListener("mouseover", kl_forschZeit, true);
                    forschLinks[i].addEventListener("mouseout", clr, true);

                }
            }
        } else if (doc.location.href.search(/page=kauf11(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.wb")) {
                var mainTable = kl_eval(doc,"//td/form/table");
                //var mainTable = FindeTags(doc, "TABLE", new Function("Kn", "return (Kn.parentNode.nodeName == 'FORM' && Kn.parentNode.parentNode.nodeName == 'TD');"));

                var mainTB = mainTable[0].firstChild;

                for (i = 1; i < mainTB.childNodes.length; i++) {
                    try{
                        mainTB.childNodes[i].lastChild.firstChild.addEventListener("keyup", kl_berechneWerbung, true);
                    }catch(e){
                        continue;
                    }
                }
                EinfuegenHinter(NeuesElement(doc, "font", "", "id", "wb"), mainTable[0].nextSibling.firstChild);
                doc.getElementById("wb").textContent = loca[lang]["wb"];
            }
        } else if (doc.location.href.search(/page=kauf(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.wb")) {
            /*var a = FindeTags(doc,"A", new Function("Kn","return (Kn.textContent.search('werben') > -1);"));
              wb = parseFloat(a[0].parentNode.firstChild.textContent);*/
            }
            if (kl_prefManager.getBoolPref("extensions.ks.menupreis")) {

                var mTD = kl_eval(doc,"//td/a[position()=last() and contains(@href,'kauf10')]/..")[0];

                //var mTD = FindeTags(doc,"TD", new Function("Kn","return (Kn.lastChild.href.search('kauf10') > -1);"))[0];

                var oldHTML = mTD.innerHTML.substring(mTD.innerHTML.search("<a"),mTD.innerHTML.length);
                var preis = mTD.innerHTML.substring(0,mTD.innerHTML.search(loca[lang]["c"])-1);
                preis = preis.replace(loca[lang]["tausend"],"");

                if ((preis.length - 1) < 1) var size = 1;
                else var size = preis.length -1 ;

                mTD.innerHTML = "<table><tr><td><form action='"+doc.location.pathname.substring(1,doc.location.pathname.length)+doc.location.search+"' method='post' style='margin: 0px;'><input type='hidden' value='2' name='neu'><input type='text' name='neu_preis' maxlength='30' size='"+size+"' value='"+preis+"'><div style='visibility: hidden;'></div></form></td><td> "+loca[lang]["c"]+"</td></tr></table>"+oldHTML;
            }

        } else if (doc.location.href.search(/page=uebersicht(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.igmfax")){

                doc.body.lastChild.addEventListener("click", function(e) {
                    if (e.button == 0)clr();
                }, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                over = doc.getElementById("klDiv");

                var tBody = kl_eval(doc,"//td/div[@align='center']")[0].firstChild.firstChild.lastChild.firstChild.firstChild.firstChild;
                //var tBody = FindeTags(doc, "DIV", new Function("Kn", "return (Kn.getAttribute('align') == 'center' && Kn.parentNode.nodeName == 'TD');"))[0].firstChild.firstChild.lastChild.firstChild.firstChild.firstChild;
                var img;
                for(i =0;i < tBody.childNodes.length;i++){

                    img = NeuesElement(doc,"img","","src","chrome://kapiland/skin/igm.png","style","height: 12px; padding-left: 2px; padding-right: 2px; cursor: pointer;");

                    img.addEventListener("click",kl_igmPopup,true);

                    EinfuegenHinter(img,tBody.childNodes[i].firstChild.childNodes[2]);

                }
            }
            if (kl_prefManager.getBoolPref("extensions.ks.todo")){
                var todo = new kl_notizbuch(doc);
                todo.set();
                todo.move(600,150);
                todo.show();

            }
        }else if (doc.location.href.search(/page=verw_p(&|$)/) > -1) {

            var mainForm = kl_eval(doc,"//form[@name='form1' and not(@id='kss')]");
            //var mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.getAttribute('name') == 'form1' && Kn.getAttribute('id') != 'kss');"));

            if (kl_prefManager.getBoolPref("extensions.ks.saveq")){
                var quali = kl_eval(doc,"//input[@name='vq']")[0];
                quali.value = kl_getQuali(doc,lang);
                quali.addEventListener("keyup", kl_saveQuali,true);
                var pselect = kl_eval(doc,"//select[@name='vprod']")[0];
                pselect.selectedIndex = kl_getProdukt(doc,lang);
                pselect.addEventListener("change", kl_saveQuali,true);

            }

            var mTB = mainForm[0].lastChild.firstChild;
            if (kl_prefManager.getBoolPref("extensions.ks.verwaltsort")){
                var gebs = new Array();


                for (i = 1;mTB.childNodes.length != 1; i++) {
                    gebs.push(mTB.childNodes[1].cloneNode(true));
                    mTB.removeChild(mTB.childNodes[1]);
                }
                gebs.sort(sortSize);

                var verwPref = NeuesElement(doc,"A",loca[lang]["prefs"],"style","cursor: pointer;");
                verwPref.addEventListener("click",function(e){
                    window.openDialog("chrome://kapiland/content/verwalt.xul",
                        "verwPref", "chrome",
                        {
                            art: doc.location.href.match(/art=([0-9]+)./)[1],
                            produkte: kl_eval(doc,"//select[@name='vprod']/option"),
                            lang: lang,
                            welt: kl_getWelt(doc.location.host),
                            gBrowser: gBrowser
                        });

                },true);
                mTB.firstChild.childNodes[1].appendChild(verwPref);

                var qm;
                var lqm = "";
                var hTB = mTB.parentNode.parentNode.parentNode;
                if(kl_isWelt5(doc.location)) {
                    // Quick&Dirty-Fix für Welt 5
                    hTB = hTB.parentNode;
                }
                hTB.removeChild(hTB.childNodes[2]);
                for (k = 0; k < gebs.length; k++) {
                    try{
                        qm = gebs[k].textContent.match(/([0-9]+)( |)m²/)[1];
                        if (qm != lqm){
                            var qtr = NeuesElement(doc,"TR","","id","ksm");

                            EinfuegenHinter(NeuesElement(doc,"A",qm+"m²","href","#"+qm+"qm","style","font-weight: bold; padding: 0px 3px 0px 3px;"),hTB.childNodes[1]);
                            EinfuegenHinter(doc.createTextNode(" "),hTB.childNodes[1]);

                            qtr.appendChild(NeuesElement(doc,"TD","<b>"+qm+"m²</b>","style","border-top: 1px groove;padding-left: 10px;","colspan","5","id","kq"+qm));
                            qtr.firstChild.appendChild(NeuesElement(doc,"INPUT","","size","7","style","margin: 0px 10px 0px 10px;","value", "DD:HH:MM"));

                            qtr.firstChild.lastChild.addEventListener("keyup",kl_prodPremium, true);
                            qtr.firstChild.lastChild.addEventListener("focus",empty, true);


                            qtr.firstChild.appendChild(NeuesElement(doc,"A",loca[lang]["alle"],"style","cursor: pointer;","name",qm+"qm"));

                            qtr.firstChild.lastChild.addEventListener("click", kl_alleq, true);


                            qtr.firstChild.appendChild(NeuesElement(doc,"A",loca[lang]["afertig"],"style","margin: 0px 10px 0px 10px;cursor: pointer;"));

                            qtr.firstChild.lastChild.addEventListener("click", kl_alleqBereite, true);

                            qtr.firstChild.appendChild(NeuesElement(doc,"A","("+loca[lang]["nachoben"]+")","href","#top"));



                            mTB.appendChild(qtr);
                        }
                        lqm = qm;
                    }catch(e){}
                    mTB.appendChild(gebs[k]);
                }

                var w = 0;
                for (i = 1; i < mTB.childNodes.length; i++) {

                    if (w == 0) {
                        for (k = 0; k < mTB.childNodes[i].childNodes.length; k++) {
                            if (mTB.childNodes[i].childNodes[k].nodeName != "#text" && mTB.childNodes[i].getAttribute("id") != "ksm") {
                                mTB.childNodes[i].childNodes[k].setAttribute("class", "white");
                            }
                        }
                        w = 1;
                    } else {
                        for (k = 0; k < mTB.childNodes[i].childNodes.length; k++) {
                            if (mTB.childNodes[i].childNodes[k].nodeName != "#text" && mTB.childNodes[i].getAttribute("id") != "ksm") {
                                mTB.childNodes[i].childNodes[k].setAttribute("class", "white2");
                            }
                        }
                        w = 0;
                    }
                }
                kl_eval(doc,"//select[@name='vprod']")[0].addEventListener("change",kl_prodPremium,true);
            }
            if (kl_prefManager.getBoolPref("extensions.ks.verwaltbereit")){
                mTB.appendChild(NeuesElement(doc,"TR","","id","kstr"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD",loca[lang]["afertig"],"class","white","align","left","valign","top"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD","&nbsp;","class","white","colspan","3"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD","<input id='ksbereite' value='' type='checkbox'>","class","white","align","right","valign","top"));

                doc.getElementById("ksbereite").addEventListener("click", kl_alleBereiten, true);

            }
        }
        else if (doc.location.href.search(/page=verw_k(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.verwaltbereit")){
                var mainForm = kl_eval(doc,"//form[@name='form1' and not(@id='kss')]");
                //var mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.getAttribute('name') == 'form1' && Kn.getAttribute('id') != 'kss');"));
                var mTB = mainForm[0].lastChild.firstChild;

                mTB.appendChild(NeuesElement(doc,"TR","","id","kstr"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD",loca[lang]["afertig"],"class","white","align","left","valign","top"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD","&nbsp;","class","white","colspan","3"));
                doc.getElementById("kstr").appendChild(NeuesElement(doc,"TD","<input id='ksbereite' value='' type='checkbox'>","class","white","align","right","valign","top"));

                doc.getElementById("ksbereite").addEventListener("click", kl_alleBereiten, true);
            }
            }
        else if (doc.location.href.search(/page=stats(2|3)(&|$)/) > -1) {
            if (lang == "de"){
                var w = extract(docloc,"welt","-kapiland");
                var l = extract(docloc,"welche=","&");
                if (l.length != 1)l = 0;

                var mTB = kl_eval(doc,"//tbody[count(*) > 33]")[0];
                //var mTB = FindeTags(doc, "TBODY", new Function("Kn", "return (Kn.childNodes.length > 33);"))[0];

                var v=0;
                if (kl_prefManager.getBoolPref("extensions.ks.statsakt")){
                    var s2 = false;
                    var p3 = false;
                    if (docloc.search("page=stats3") > -1) p3 = true;
                    if (docloc.search("&start=30") > -1) s2 = true;
                    mTB.setAttribute("id","statstable");
                    // loading

                    mTB.appendChild(NeuesElement(doc,"TR","","id","loadingtr"));
                    doc.getElementById("loadingtr").appendChild(NeuesElement(doc,"td","<font align='right' style='font-weight:bold; font-size:10px; align: right;' id='kstat'>Stats Loading <img src='chrome://kapiland/skin/loading.gif' style='vertical-align: middle;'></img></font>","align","right","colspan","10"));

                    v = 1;
                    kl_statRequest(doc,w,l,s2,p3);
                }
                if (kl_prefManager.getBoolPref("extensions.ks.grphstat")){

                    if (kl_prefManager.getBoolPref("extensions.ks.grphaut")){
                        if (docloc.search(/page=stats2(&|$)/) > -1){
                            var m1 = "preis";
                            var m2 = "quali";
                        }else{
                            var m1 = "angebot";
                            var m2 = "nachfrage";
                        }
                    }else{
                        switch(kl_prefManager.getIntPref("extensions.ks.grph1")){
                            case 0:
                                var m1 = "angebot";
                                break;
                            case 1:
                                var m1 = "nachfrage";
                                break;
                            case 2:
                                var m1 = "preis";
                                break;
                            case 3:
                                var m1 = "quali";
                                break;
                        }
                        switch(kl_prefManager.getIntPref("extensions.ks.grph2")){
                            case 0:
                                var m2 = "angebot";
                                break;
                            case 1:
                                var m2 = "nachfrage";
                                break;
                            case 2:
                                var m2 = "preis";
                                break;
                            case 3:
                                var m2 = "quali";
                                break;
                            case 4:
                                var m2 = "null";
                                break;
                        }
                    }


                    mTB.childNodes[0].appendChild(NeuesElement(doc,"TD","<b>Graph</b>","class","white2"));

                    for(i=1;i < mTB.childNodes.length -v;i++){
                        mTB.childNodes[i].appendChild(NeuesElement(doc,"TD","<center><a style='cursor: pointer; vertical-align: middle;' href='http://stats.kapigeco.de/graph.php?w="+w+"&l="+l+"&m1="+m1+"&m2="+m2+"&p="+unescape(mTB.childNodes[i].childNodes[0].textContent)+"' target='_blank'><img border='0' src='chrome://kapiland/skin/graph.png' width='22' height='13'></img></a></center>","class",mTB.childNodes[i].childNodes[0].getAttribute("class")));

                    }
                }
            }
            }else if (doc.location.href.search(/page=verw_k2(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.vkpremium")) {

                var mainForm = kl_eval(doc,"//td/form[not(@id='kss')]")[0];
                //var mainForm = FindeTags(doc, "FORM", new Function("Kn", "return (Kn.parentNode.nodeName == 'TD' && Kn.getAttribute('id') != 'kss');"))[0];
                var rows = mainForm.getElementsByTagName("TABLE")[0].getElementsByTagName("TR");
                var el;
                for(var i=1;i < rows.length;i++){

                    el = NeuesElement(doc,"A","<font class='klein' style='padding-left: 20px;cursor: pointer;'>"+loca[lang]["alles"]+"</font>");
                    rows[i].firstChild.appendChild(el);
                    el.addEventListener("click", kl_verwk, true);

                }
                prozent = NeuesElement(doc,"B",loca[lang]["vk"]+"<input class='klein' style='color: green;' size='3' value='145' type='text' id='ksvk'>","class","klein","style","color: black;");
                EinfuegenHinter(prozent,mainForm.getElementsByTagName("TABLE")[0]);
                prozent.lastChild.addEventListener("keyup", kl_verwk, true);

            }
            }else if (doc.location.href.search(/page=verw_(ap|ak)(&|$)/) > -1) {
            kl_eval(doc,"//input[@name='ausbau']")[0].addEventListener("click",function(e){
                ausbauZahl = 0;
                var ausbau = kl_eval(doc,"//input[@name='vgeb[]']");
                for (var i =0;i < ausbau.length;i++){
                    if (ausbau[i].checked) ausbauZahl++;
                }

            }, true)


        }else if (doc.location.href.search(/page=verw_(ap|ak)2(&|$)/) > -1) {

            if (kl_prefManager.getBoolPref("extensions.ks.ausbaupa")){

                var mTB = kl_eval(doc,"//td/div/form/table/tbody")[0];

                EinfuegenHinter(NeuesElement(doc,"TD","<b>"+loca[lang]["diff"]+"</b>","class","white2","valign","top"),mTB.firstChild.childNodes[1]);
                var k = 0;
                var last = "";
                var welche = new Array("","11","19","56");
                for(i =1;i < mTB.childNodes.length;i++){
                    try{
                        if (mTB.childNodes[i].childNodes[1].textContent != last) k++;

                        last = mTB.childNodes[i].childNodes[1].textContent;
                        mTB.childNodes[i].firstChild.setAttribute("mtyp",k);

                        var titel = mTB.childNodes[i].childNodes[1].firstChild.nodeValue.substring(1,mTB.childNodes[i].childNodes[1].firstChild.nodeValue.length);
                        var a = NeuesElement(doc,"A",titel,"href","http://" + doc.location.host + doc.location.pathname + "?" + "page=markt2&UIN=" + extract(doc.location.search, "UIN=", "&") + "&search="+welche[k]+"&welche=2&sort=");

                        mTB.childNodes[i].childNodes[1].replaceChild(a,mTB.childNodes[i].childNodes[1].firstChild);
                        mTB.childNodes[i].childNodes[1].insertBefore(doc.createTextNode(" "),mTB.childNodes[i].childNodes[1].firstChild);

                        EinfuegenHinter(NeuesElement(doc,"TD","","class",mTB.childNodes[i].firstChild.getAttribute("class")),mTB.childNodes[i].firstChild);


                    }catch(e){
                        continue;
                    }

                }

                var qinput = kl_eval(doc,"//input[@name='num_ausbau']")[0];
                qinput .addEventListener("keyup",kl_adminAusbau, true);
                EinfuegenHinter(NeuesElement(doc,"B","<font id='qmfont'> ≙ 0 m²</font>"),qinput.nextSibling);


            }
        }else if (doc.location.href.search(/page=markt(4|7)(&|$)/) > -1 && doc.location.href.search(/sort=1(&|$)/) == -1) {

            if (kl_prefManager.getBoolPref("extensions.ks.igmmarkt")){


                doc.body.lastChild.addEventListener("click", function(e) {
                    if (e.button == 0)clr();
                }, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                over = doc.getElementById("klDiv");

                var tBody = kl_eval(doc,"//tr/td[@class ='white2']/*[position() = '1' and name()='TABLE']/..")[0].lastChild.lastChild;

                //var tBody = FindeTags(doc, "TD", new Function("Kn", "return (Kn.parentNode.nodeName == 'TR' && Kn.getAttribute('class') == 'white2' && Kn.firstChild.nodeName == 'TABLE');"))[0].firstChild.firstChild;


                var img;

                for (var i =1; i < tBody.childNodes.length;i++){

                    img = NeuesElement(doc,"img","","src","chrome://kapiland/skin/igm.png","style","height: 10px; padding-left: 2px; padding-right: 2px; cursor: pointer;");

                    img.addEventListener("click",kl_igmPopup,true);

                    tBody.childNodes[i].childNodes[2].appendChild(img);

                }

            }
        }else if (doc.location.href.search(/page=markt(2|5)(&|$)/) > -1) {
            if (kl_prefManager.getBoolPref("extensions.ks.igmmarkt")) {

                doc.body.lastChild.addEventListener("click", function(e) {
                    if (e.button == 0)clr();
                }, true);

                doc.body.appendChild(NeuesElement(doc, "div", "", "id", "klDiv", "style", "visibility:hidden; Z-INDEX: 10000; LEFT: -1px; POSITION: absolute; top: 9px; border:outset; border-width:2px; border-color:#fAffe0;"));

                over = doc.getElementById("klDiv");


                var tBody = kl_eval(doc,"//tr/td[@class='white2']/*[position() = '1' and name()='TABLE']/..//table/tbody");
                tBody = tBody[tBody.length - 1];

                //var tBody = FindeTags(doc, "TD", new Function("Kn", "return (Kn.parentNode.nodeName == 'TR' && Kn.getAttribute('class') == 'white2' && Kn.firstChild.nodeName == 'TABLE');"))[0].lastChild.firstChild.firstChild.firstChild.firstChild.firstChild;


                var img;

                for (i =1; i < tBody.childNodes.length;i++){

                    img = NeuesElement(doc,"img","","src","chrome://kapiland/skin/igm.png","style","height: 10px; padding-left: 2px; padding-right: 2px; cursor: pointer;");

                    img.addEventListener("click",kl_igmPopup,true);

                    tBody.childNodes[i].childNodes[1].appendChild(img);

                }

            }
        }else if (doc.location.href.search(/page=nachricht2(&|$)/) > -1) {

            if (igmforw && doc.body.textContent.search(loca[lang]["fehler"]) == -1){
                igmforw = false;
                gBrowser.selectedBrowser.contentDocument.location.replace(window.content.history[window.content.history.length - 2]);
            }

        }

        // Ans Ende gelagerte Funktionen
        try{

            if (doc.location.href.search("s5.kapilands.eu") > -1){
                var menue = kl_eval(doc,"//td/div")[0];
            }
            else{
                var menue = kl_eval(doc,"//a[contains(@href,'levels')]/..")[0];
            }
            //var menue = FindeTags(doc, "TD", new Function("Kn", "return (Kn.getAttribute('class') == 'white' && (Kn.firstChild.nodeName == 'FONT' || Kn.firstChild.nodeName == 'B') && Kn.parentNode.nodeName == 'TR');"));

            if (kl_prefManager.getBoolPref("extensions.ks.notizbuch")){
                var notizbuch = NeuesElement(doc, "font", loca[lang]["notizbuch"], "style", "font-weight: bold;cursor: pointer;");

                var nb = new kl_notizbuch(doc);
                nb.set();
                nb.moveTo(nx,ny);
                notizbuch.addEventListener("click",nb.change,true);
                menue.appendChild(doc.createElement("BR"));
                menue.appendChild(notizbuch);
                if (show_nb){
                    nb.show();
                }
            }
        }catch(e){}

        if (doc.location.pathname == "/" || doc.location.pathname == "/index.php" || doc.location.href.search(/kapilands?.(de|com|fr|eu)[/]main[.]php4$/) > -1) {
            //noinspection JSUnusedLocalSymbols
            try {
                var server = kl_eval(doc,"//select[@name='server']");
                //var server = FindeTags(doc, "SELECT", new Function("Kn", "return (Kn.name == 'server');"));
                
                // Only select the server if it is available
                if(server[0].options.length > kl_prefManager.getIntPref("extensions.ks.welt")) {
                	server[0].options.selectedIndex = kl_prefManager.getIntPref("extensions.ks.welt");
                }
            } catch(e){
            }
        }
    //ende = new Date();
    //doc.body.appendChild(NeuesElement(doc,"font","Execution Time:"+((parseFloat(ende.getTime())-parseFloat(start.getTime()))/1000)+" s","style","color: white;"));

    }
}

kl_init();

